![](/img/trans.png)
[英]Angular 8: Custom HTML Attribute doesn't work inside component html
[英]Custom attribute doesn't work
我做了一個自定義屬性,為每個鏈接添加標題。
<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 。 我怎樣才能解決這個問題。
遍歷元素標簽並追加到元素標簽
$('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>
您可以使用循環實現與以下相同的效果:
$('[nameOf]').each(function(){
$(this).append('<span class="title">' + $(this).attr("nameOf") + '</span>')
});
但按照W3C的規則,你不能使用nameOf
在屬性a
標簽,所以你可以使用使用data-nameof
代替。
在HTML中,您無法在駝峰式的情況下創建自定義屬性。 如果要在自定義屬性中添加更多單詞,則需要添加-
符號。 因此,就您的情況而言。
<a href="#" name-of="The Flower" id="ex1"></a>
稍后,建議您使用駱駝套進行搜索。
$(element).attr('nameOf');
您示例中的this
是window,它不知道它應該是對鏈接的引用。 為了使用它,您將需要在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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.