【问题标题】:how to get actual content of an object after being replaceWith('something') in jquery在jquery中被replaceWith('something')后如何获取对象的实际内容
【发布时间】:2013-02-28 02:00:46
【问题描述】:

我有这个代码

$(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'的类名,即'medium'

【问题讨论】:

    标签: jquery this replacewith


    【解决方案1】:

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

    $('.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() 查找新元素而不是旧元素。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • thx andrew,我的意图是能够访问实际 'obj' 中的所有内容,$('.size').click(function(){ var obj = $(this), repl = $('
        whats up man ??!
        '); obj.replaceWith(repl); alert(obj.find( 'span').attr('class')); // 这将打印 'undefined' // 我想从实际的 'obj' 中获取类名 });
      • 但是你知道你刚刚给它分配了size,那么为什么不只是提醒size呢?就这样做:replacement.find('span').attr('class') 如果你真的必须这样做
      • 是的,安德鲁,你的代码首先解决了我的问题。但我想我误解了。这是最终结果jsfiddle.net/HCXaK/1
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-20
      • 2011-06-04
      相关资源
      最近更新 更多