【问题标题】:Modify in-memory Jquery element and return it修改内存中的 Jquery 元素并返回它
【发布时间】:2015-07-29 04:17:45
【问题描述】:

为什么这个脚本不返回修改后的元素?
该元素在函数中确实发生了变化,但没有正确返回。

<script>
x = "<div></div><div></div><div></div><p></p>";
function modify (x) {
    $(x).find('div').each(function(index){
        $(this).html('content text'); 
        $(this).addClass('test') ;
    }); 
    return $(x);
}
modify (x);
</script>

【问题讨论】:

  • 那是因为当您使用.find() 时,它会在您的元素中查找子节点。您必须将 HTML 包装在一个包装器元素中(就像另一个 &lt;div&gt; 一样),并在完成后将其解包,然后再将其注入 DOM。可能相关:stackoverflow.com/questions/7159426/…
  • 您如何确定它是否已更改?您的代码中没有任何内容使用/回显x

标签: javascript jquery


【解决方案1】:

每个函数中的this 不是指x 的元素。您需要声明一个变量来表示 x 元素 this 就像这样 -

$(x).find('div').each(function(index, that){
    $(that).html('content text'); 
    $(that).addClass('test') ;
}); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-05
    • 2016-11-11
    • 1970-01-01
    • 2010-10-27
    • 2017-12-01
    • 2011-03-02
    • 1970-01-01
    相关资源
    最近更新 更多