0

我正在尝试为 dom 元素创建一个 var 来清理内容,但它并没有给我预期的结果。我认为这样做的原因是因为在我运行该函数时尚未创建该元素。我可以在调用 .prepend() 之后移动 var,但是如果我想将所有 var 保留在顶部怎么办?

在此脚本中的某处添加 .on() 会解决我的问题,还是应该在运行 .prepend 后将 var 向下移动几行,而忘记将 vars 保持在顶部?

    (function () {
        var cp = $(".call-out p")

        $('li').eq(2).prepend('hi');
        $('div.call-out').prepend("<p>MY UL</p>");
        cp.css({
             'font-size': '3em',
             'background': 'orange'
        });
        cp.animate({
              width: "1000px",
              height: "1250px"
        });
        cp.click(function (e) {
             $(this).animate({
              width: "125px",
              height: "90px"
       });
     });
   })();
4

1 回答 1

1

可以从 html 构造 jQuery 对象,因此您可以这样做:

var cp = $("<p>MY UL</p>").css({....});/* can add css or event handlers before insert into DOM*/

$('li').eq(2).prepend('hi');
$('div.call-out').prepend(cp);
 /* although created outside the DOM, once inserted the object still exists to use jQuery methods on*/
 cp.animate({....});

诸如此类的方法html()prepend()接受多种类型作为内容参数,包括 jQuery 对象

仔细查看API 文档 中的content定义:http: //api.jquery.com/prepend/prepend()

于 2012-11-05T07:20:36.907 回答