代码之家  ›  专栏  ›  技术社区  ›  Crashalot

jQuery/JavaScript:比较两个元素及其属性

  •  0
  • Crashalot  · 技术社区  · 6 年前

    This question this question 解释如何比较两个jQuery元素/对象的内容?

    要素1:

    <div id="A" width="200" height="200" style="stuff"></div>
    

    <div id="B" width="300" height="300" style="differentstuff"></div>
    

    要素3:

    <div id="C" width="200" height="200" style="stuff"></div>
    

    假设所有三个元素的内容与 $.html()

    是否有本机方法来执行此操作,或者必须手动检查每个属性?理想情况下,有一种方法可以获取元素的“属性内容”作为比较的方法。

    1 回复  |  直到 6 年前
        1
  •  1
  •   CertainPerformance    6 年前

    您可以检查元素的 outerHTML 并检查第一个 < > (即标记和属性字符串)相同:

    const elmToAttribString = elm => elm.outerHTML.match(/<[^>]+>/)[0];
    const check = (elm1, elm2) => elmToAttribString(elm1) === elmToAttribString(elm2);
    
    const [d1, d2, d3] = $('div');
    console.log(check(d1, d2));
    console.log(check(d1, d3));
    console.log(check(d2, d3));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="A" width="200" height="200" style="stuff"></div>
    <div id="A" width="300" height="300" style="differentstuff"></div>
    <div id="A" width="200" height="200" style="stuff"></div>

    但是,请注意,这会检查 元素在HTML中列出的顺序,而不是 性质

    如果属性可以是不同的顺序,或者它们之间可以有不同的分隔符(例如,属性值对之间不只是一个空格),那么您必须提取每个属性以进行检查,可能需要转换 .attributes

    const elmToAttribString = elm => JSON.stringify(
      [...elm.attributes]
        .map(({ name, value }) => ({ name, value }))
        .sort((a, b) => a.name.localeCompare(b.name))
    );
    const check = (elm1, elm2) => elmToAttribString(elm1) === elmToAttribString(elm2);
    
    const [d1, d2, d3] = $('div');
    console.log(check(d1, d2));
    console.log(check(d1, d3));
    console.log(check(d2, d3));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    first item has different order, weird spacing:
    <div width="200" id="A"        height="200" style="stuff"></div>
    <div id="A" width="300" height="300" style="differentstuff"></div>
    <div id="A" width="200" height="200" style="stuff"></div>