【问题标题】:Add a string of html attributes to a html element将一串 html 属性添加到 html 元素
【发布时间】:2017-10-05 01:26:55
【问题描述】:

我有一串用有效 html 编写的属性,我想将这些属性放在实际的 html element 上(而不是元素的 html string)。

例如,我在合理命名的attributesStr 变量中有属性字符串,我想将这些属性添加到#htmlElement div。

var attributesStr = "";
attributesStr += " class='regularClass'"; // Needs to handle key value attributes.
attributesStr += " title='Title... with spaces!'"; // And attributes with spaces.
attributesStr += " style='color: red; font-weight: bold;'"; // And style with multiple properties.
attributesStr += " data-attributenovalue"; // And attributes with no value.

// Your special code to add the attributes to `#htmlElement` goes here.
<div id="htmlElement">
    The HTML element!
</div>

运行 JQuery / JavaScript 代码后,#htmlElement 应如下所示:

<div id="htmlElement" class='regularClass' title='Title... with spaces!' style='color: red; font-weight: bold;' data-attributenovalue>
    The HTML element!
</div>

如何在 JavaScript 或 Jquery 中做到这一点?


第一次尝试:我想我可以通过 .split()ing attributesStr 在空格上执行此操作,然后在 = 上拆分每个单独的属性键值对,然后迭代该数组并添加每个键值对使用 JQuery 的 .prop().attr(),但这不起作用有两个原因:

  1. styletitle 属性会失败,因为它们有空格。
  2. 可能在没有值的属性上失败。

【问题讨论】:

  • attributesStr.match(/[^\s=]+(=['][^']*['])?/g) 这会让你第一次分裂
  • 您通过破解预先构建的字符串使这变得比需要的更难。您不能在构建该字符串时应用样式吗?或者甚至创建一个具有这些值的对象以供以后应用?
  • @RoryMcCrossan 我已经找到了一个不同的解决方案来解决我原来的问题,我只是好奇是否有办法在 JS/JQuery 中做到这一点:)
  • @tallberg 如果您认为自己有一个可行的解决方案,请随时发布答案:)
  • 当然,有很多方法可以做任何事情,但由于各种原因,其中大多数都不是最好的方法。

标签: javascript jquery html attributes


【解决方案1】:

获取attributesStr 并将其插入现有的outerHTML。为此,您需要通过删除现有标记、注入字符串并放回 html 的其余部分来重建节点。

var attributesStr = "";
attributesStr += " class='regularClass'"; // Needs to handle key value attributes.
attributesStr += " title='Title... with spaces!'"; // And attributes with spaces.
attributesStr += " style='color: red; font-weight: bold;'"; // And style with multiple properties.
attributesStr += " data-attributenovalue"; // And attributes with no value.

var element = document.getElementById('htmlElement');

var tag = element.tagName;

element.outerHTML = '<' + tag + attributesStr + element.outerHTML.substring(tag.length + 1);
<div id="htmlElement">
  The HTML element!
</div>

【讨论】:

  • 哇!这确实有效,但是如果您检查该元素,您会发现它在旧的#htmlElement 中添加了一个新元素。尝试使用outerHtml 来解决这个问题。
  • 是的,愚蠢的 jQuery 的html()。还不如根本不使用它
【解决方案2】:

您可以使用 .attr() 在 jquery 中执行此操作。这是工作的sn-p。

click here for attr() usage

$(document).ready(function(){
$("#htmlElement").attr("class", "regularClass");
$("#htmlElement").attr("title", "Title... with spaces!");
$("#htmlElement").attr("style", "color: red; font-weight: bold");
$("#htmlElement").attr("data-attributenovalue",true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="htmlElement">
    The HTML element!
</div>

【讨论】:

  • 我必须使用具有所有属性的字符串,我绝对不能修改该字符串的源格式。我将 attributesStr 变量作为字符串外观的示例。
  • 您想将字符串与所有属性一起使用,而不是使用 attr 单独添加它吗?
  • 是的,完美运行 :) 感谢您的回答。
【解决方案3】:

试试这个:

var dummHTML = $("<div "+attributesStr+"></div>");   
$.each(dummHTML[0].attributes, function(i,v){
 $('#htmlElement').attr(v.nodeName,v.nodeValue);
});

【讨论】:

    【解决方案4】:

    也许不是最好的选择,但如果需要使用完整的字符串:

    想法是:获取元素的内容,然后将其删除并使用新属性再次创建它:

    var attributesStr = "";
    attributesStr += " class='regularClass'"; // Needs to handle key value attributes.
    attributesStr += " title='Title... with spaces!'"; // And attributes with spaces.
    attributesStr += " style='color: red; font-weight: bold;'"; // And style with multiple properties.
    attributesStr += " data-attributenovalue"; // And attributes with no value.
    
    // Your special code to add the attributes to `#htmlElement` goes here.
    var $innerHTML = $("#htmlElement").html()
    $("#htmlElement").remove()
    var $newElement = "<div id='htmlElement' " + attributesStr + ">" + $innerHTML + "</div>" 
    
    $("body").after($newElement)
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="htmlElement">
        The HTML element!
    </div>

    【讨论】:

      【解决方案5】:

      为什么不用','分隔你的字符串

      var attributesStr = "";
      attributesStr = attributesStr + " class='regularClass'," ; // Needs to handle key value attributes.
      attributesStr = attributesStr +" title='Title... with spaces!',"; // And attributes with spaces.
      attributesStr = attributesStr +" style='color: red; font-weight: bold;',"; // And style with multiple properties.
      attributesStr = attributesStr +" data-attributenovalue,"; // And attributes with no value.
      
      var array = attributesStr.split(',');
      
      array.forEach(function(item){
       property = item.split('=');
       $('#htmlElement').attr(property[0].trim());
       if(property[1]) $('#htmlElement').attr(property[0].trim(), property[1].trim());
      });
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <div id="htmlElement">
          The HTML element!
      </div>

      【讨论】:

      • 我必须使用具有所有属性的字符串,我绝对不能修改该字符串的源格式。我将 attributesStr 变量作为字符串外观的示例。
      【解决方案6】:

      这会让你第一次分裂

      attributesStr.match(/[^\s=]+(=['][^']*['])?/g)
      

      结果:

      ["class='regularClass'", "title='Title... with spaces!'", "style='color: red; font-weight: bold;'", "data-attributenovalue"]
      

      然后在foreach 中,您可以按照您的建议处理 attrs。

      【讨论】:

      • 好的,这看起来可能有效。你能包括其余的代码来处理 attrs 吗?那么它无疑会起作用。
      猜你喜欢
      • 2015-07-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-30
      • 2021-01-04
      • 2016-01-01
      • 1970-01-01
      • 2011-12-26
      • 1970-01-01
      相关资源
      最近更新 更多