【问题标题】:Custom attribute doesn't work自定义属性不起作用
【发布时间】:2018-02-03 04:49:00
【问题描述】:

我做了一个自定义属性来为每个链接添加一个标题。

<a href="#" nameOf="The Flower" id="ex1"></a>
<a href="#" nameOf="The Tree" id="ex2"></a>

这里是 jQuery 代码

$('#ex1,#ex2').append('<span class="title">'+$(this).attr("nameOf")+'</span>');

但链接显示为undefined。我该如何解决这个问题。

【问题讨论】:

  • 过去使用自定义属性,但由于 HTML5 支持全局 data-* 属性,强烈建议改用 data-* 属性。还建议对 HTML 标记和属性使用所有小写字母。所以改成data-nameof

标签: javascript jquery html


【解决方案1】:

遍历元素标签并附加到它

$('a').each(function(i, v) {
  $(this).append('<span class="title">' + $(this).attr("nameOf") + '</span>');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" nameOf="The Flower" id="ex1"></a>
<a href="#" nameOf="The Tree" id="ex2"></a>

【讨论】:

    【解决方案2】:

    您示例中的this 是窗口,它不知道它应该是对链接的引用。为了使用它,您需要在 append() 中使用一个函数并返回字符串。

    $('#ex1,#ex2').append( function() { return '&lt;span class="title"&gt;'+$(this).attr("nameOf")+'&lt;/span&gt;'});
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <a href="#" nameOf="The Flower" id="ex1"></a>
    <a href="#" nameOf="The Tree" id="ex2"></a>

    如果您根本不想使用 JavaScript 并让文本显示在链接中,总有一个 CSS 解决方案。

    a[nameOf]::before {
      content: attr(nameOf)
    }
    <a href="#" nameOf="The Flower" id="ex1"></a>
    <a href="#" nameOf="The Tree" id="ex2"></a>

    【讨论】:

      【解决方案3】:

      您可以使用循环实现以下相同的效果:

      $('[nameOf]').each(function(){
          $(this).append('<span class="title">' + $(this).attr("nameOf") + '</span>')
      });
      

      但根据w3c 规则,您不能在a 标记中使用nameOf 属性,因此您可以改用data-nameof

      【讨论】:

        【解决方案4】:

        在 HTML 中,您不能在驼峰式中创建自定义属性。如果要向自定义属性添加更多单词,则需要添加 - 符号。所以,对于你的情况,做。

        <a href="#" name-of="The Flower" id="ex1"></a>
        

        稍后,为了搜索,我建议你使用骆驼案。

        $(element).attr('nameOf');
        

        【讨论】:

        猜你喜欢
        • 2016-10-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-22
        • 2018-12-20
        • 2016-05-14
        • 1970-01-01
        相关资源
        最近更新 更多