我做了一个自定义属性来为每个链接添加一个标题。
<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>');
但链接显示为未定义。我该如何解决这个问题。
遍历元素标签并附加到它
$('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>
示例中的this
是窗口,它不知道它应该是对链接的引用。为了使用它,你需要在 append(( 中使用一个函数并返回字符串。
$('#ex1,#ex2').append( function() { return '<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>
如果你根本不想使用JavaScript,而是让文本显示在链接中,总有一个CSS解决方案。
a[nameOf]::before {
content: attr(nameOf)
}
<a href="#" nameOf="The Flower" id="ex1"></a>
<a href="#" nameOf="The Tree" id="ex2"></a>
您可以使用循环实现与以下相同的目标:
$('[nameOf]').each(function(){
$(this).append('<span class="title">' + $(this).attr("nameOf") + '</span>')
});
但根据 W3C 规则,您不能a
标签中使用nameOf
属性,因此您可以使用 data-nameof
代替。
在 HTML 中,您无法在驼峰大小写中创建自定义属性。 如果要向自定义吸引添加更多字词,则需要添加-
符号。 所以,对于你的情况,做。
<a href="#" name-of="The Flower" id="ex1"></a>
稍后,为了搜索,我建议您使用骆驼盒。
$(element).attr('nameOf');