获取包含[name]的所有跨度

时间:2017-07-17 11:04:27

标签: javascript jquery

我正在尝试检索并遍历我页面上的所有元素,这些元素都是跨度并具有名称标记。有什么想法吗?

$("span[name$='*']").each(function () {  // first pass, create name mapping               
           // Console.log(this);
            //name_map[name] = (name_map[name]) ? name + "[]" : name;
 });

<span class="col-xs-2 control-label" name="toddler">xxx</span> <-- get this
<span class="col-xs-2 control-label">xxx</span> <-- don't get this

2 个答案:

答案 0 :(得分:4)

您可以将属性放在选择器中,没有值,例如[name]。试试这个:

&#13;
&#13;
$("span[name]").addClass('foo');
&#13;
.foo { color: #C00; }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="col-xs-2 control-label" name="toddler">yes</span>
<span class="col-xs-2 control-label">no</span>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

&#13;
&#13;
var arr = $("span[name]").map(function() {
  return $(this).text()
}).get();


console.log(arr)
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="col-xs-2 control-label" name="toddler">xxx1</span>
<span class="col-xs-2 control-label">xxx</span>
&#13;
&#13;
&#13;

  1. 仅使用$('span[name]')。表示具有名称属性的跨度