[英]JavaScript - Append div based on attribute (multiple attributes)
我有兩個沒有任何內容的容器。 我想根據其他div的屬性將內容附加到這些容器中。 我唯一的麻煩是,屬性中有多個值,並用分號分隔,這破壞了我的現有代碼。
例如,我有以下div:
<div class="item-container" location="United States; United Kingdom"></div>
我的JavaScript當前如下所示:
$('.item-container').each(function () {
var location = $(this).attr('location');
if (location == "United States") { $('#american-container').append(location );}
});
現在,在location屬性僅包含“ United States”的情況下,這可以很好地工作。 但是,如果“位置”屬性中有多個值,則會中斷。
有沒有辦法確保即使存在其他值,我的“ if”語句也能正常工作?
任何幫助將不勝感激。
使用indexOf()
if (location.indexOf("United States") >-1)
如果您的代碼如下所示
$('.item-container').each(function () {
var location = $(this).attr('location');
if (location.indexOf("United States") >-1) { $('#american-container').append(location );}
if (location.indexOf("United kingdom") >-1) { $('#europe-container').append(location );}
});
然后,您已經知道要查找的內容,則可以將位置更改為if字符串,如下所示
if (location.indexOf("United States") >-1) {$('#american-container').append("United States");}
if (location.indexOf("United kingdom") >-1) {$('#europe-container').append("United kingdom");}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.