如何在jquery中替换('something')后获取对象的实际内容

时间:2010-08-26 08:55:38

标签: jquery this replacewith

我有这段代码

$(document).ready(function(){
    $('.selector').click(function(){
        obj = $(this);
        obj.replaceWith('<div class="size">whats up man ??!</div>');
        alert(obj.html());
    });
});

我想获得'obj'的新内容,即'replaceWith'

但是,

我得到旧内容......

如何获得'obj'???

的实际内容

我打算访问新的'obj'

$('.selector').click(function(){
            var obj = $(this),
            repl = $('<div class="size">whats up man ??! <span class="medium"></span></div>');
            obj.replaceWith(repl);
            alert(obj.find('span').attr('class')); //this will print 'undefined'
});

我想打印'span'的类名'media'

2 个答案:

答案 0 :(得分:10)

您更新的方法是正确的,只需要这样的调整:

$('.selector').click(function(){
  var obj = $(this),
      repl = $('<div class="size">whats up man ??! <span class="medium"></span></div>');
  obj.replaceWith(repl);
  alert(repl.find('span').attr('class')); 
});

You can test it out here。重要的变化是repl.find()查看新元素而不是旧元素。

答案 1 :(得分:3)

你为什么要这样做?你知道你用它取代了什么......

$(document).ready(function(){
    $('.selector').click(function(){
        var obj = $(this);
        var replacement = $('<div class="size">whats up man ??!</div>');
        obj.replaceWith(replacement);
        alert(replacement.html());
    });
});