【问题标题】:JQuery how to remove "id" from a part of html contentJQuery如何从部分html内容中删除“id”
【发布时间】:2011-07-08 02:43:10
【问题描述】:

我想做这样的事情:

var html = $("#media").html();
$("#multimedia-content").append(html);
$("#multimedia-content").filter("*").removeAttr("id");

第 3 行失败,我想从这部分 html 中删除所有 id 但我不知道如何进行选择。

谢谢!

【问题讨论】:

  • 为什么不在第一行调用removeAttr,或者使用$('#multimedia-content *').removeAttr('id'); 另外,如果这是jQuery >=1.6,请考虑使用.rempveProp

标签: jquery html selector


【解决方案1】:

就个人而言,我会试试这个:

$('#media')                         // grab the media content
  .clone()                          // make a duplicate of it
  //.find('*')                        // find all elements within the clone
    .removeAttr('id')               // remove their ID attributes
  //.end()                            // end the .find()
  .appendTo('#multimedia-content'); // now add it to the media container

如果您也希望 #media 丢失其 ID,请删除 .find().end() 行,否则请取消注释。

【讨论】:

  • 您的示例留下了重复的 ID!特别是“媒体”
  • @Brock:确实,媒体的 ID 没有改变,但 OP 并不打算改变它。不好的行为,是的,简单的修复,也是一个是(删除 .find().end() 调用,一切都会更好。)
  • 嗯?我没有看到任何证据表明 OP 不希望避免 重复 ID。这可能就是他首先这样做.removeAttr("id"); 的原因。但是,请将.find()-and-.end() 修复添加到您的答案中,然后再投票。
【解决方案2】:

你应该这样做:

$("#multimedia-content *").removeAttr("id");

这将删除#multimedia-content中元素的所有id

【讨论】:

    【解决方案3】:

    试试这个:

    $("*[id], #multimedia-content").removeAttr("id");
    

    这样它只会从包含 id 属性的元素中删除 id 属性。

    【讨论】:

      【解决方案4】:

      要从#multimedia-content 的任何子元素中删除任何id 属性:

      $("#multimedia-content").find().each(function() {
          $(this).removeAttr("id");
      });
      

      【讨论】:

        猜你喜欢
        • 2022-11-22
        • 2014-06-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-08
        • 1970-01-01
        • 1970-01-01
        • 2022-11-10
        相关资源
        最近更新 更多