JavaScript-基于属性追加div(多个属性)

JavaScript-基于属性追加div(多个属性),javascript,jquery,html,Javascript,Jquery,Html,我有两个没有任何内容的容器。我想根据其他div的属性将内容附加到这些容器中。我唯一的问题是,属性中有多个值,由分号分隔,这破坏了我现有的代码 例如,我有以下div: <div class="item-container" location="United States; United Kingdom"></div> 现在,在location属性仅包含“United States”的情况下,这种方法非常有效。但是,当“Location”属性中有多个值时,这将中断 有没有办

我有两个没有任何内容的容器。我想根据其他div的属性将内容附加到这些容器中。我唯一的问题是,属性中有多个值,由分号分隔,这破坏了我现有的代码

例如,我有以下div:

<div class="item-container" location="United States; United Kingdom"></div>
现在,在location属性仅包含“United States”的情况下,这种方法非常有效。但是,当“Location”属性中有多个值时,这将中断

有没有办法确保我的“如果”语句即使存在其他值也能正常工作

任何帮助都将不胜感激。

使用
indexOf()

如果您的代码如下所示

$('.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 (location.indexOf("United States") >-1) {$('#american-container').append("United States");}
    if (location.indexOf("United kingdom") >-1) {$('#europe-container').append("United kingdom");}
然后你已经知道你在寻找什么,然后你可以像这样改变if字符串的位置

$('.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 (location.indexOf("United States") >-1) {$('#american-container').append("United States");}
    if (location.indexOf("United kingdom") >-1) {$('#europe-container').append("United kingdom");}

location
不是有效属性,您应该改为使用:
data location
并使用
.data('location')
Hi Anton检索其值-感谢您的快速响应。你的建议是什么?如果(location.indexOf(“美国”)>-1{$(“#美国容器”).append(location);}-如果是这样,这包含了美国值和其他值(如英国)啊,虽然你想要所有这些,但我会做一些事情,我会更新我的答案soon@Tron如果您已经知道要追加什么,为什么不直接追加('United')?我不知道我要附加什么。我使用的是一个内容管理系统。“Location”属性会自动将输入列表的项目提取出来。我要做的是,如果碰巧得到的值是“United”,抓住它,把它推到另一个容器里。所以这是一个很大的“如果”。美国可能无法通过,但我需要考虑到它可能会通过的潜在机会。