我有点卡住了。我想使用jquery选择器获取属性值"for"
。虽然我能够成功登录到控制台,但如何在标签上获取/记录属性"for"
的值?我试过console.log(labels['for'])
,但这不是要走的路。以下是相关代码。
HTML:
<div class="inline-group" id="album_set-group">
<h2>Albums</h2>
<div class="inline-related">
<h3><b>Album:</b> <span class="inline_label">#1</span></h3>
<fieldset class="module aligned ">
<div class="form-row field-name">
<div>
<label for="id_album_set-0-name">Name:</label> <input id="id_album_set-0-name" maxlength="100" name="album_set-0-name" type="text">
</div>
</div>
<div class="form-row field-release_date">
<div class="date-field">
<label for="id_album_set-0-release_date">Release date:</label> <input id="id_album_set-0-release_date" name="album_set-0-release_date" type="text">
</div>
</div>
</fieldset>
</div>
</div>
JAVASCRIPT:
$(document).ready(function() {
var labels = $( "#album_set-group" ).find( "label" );
console.log(labels);
});
答案 0 :(得分:2)
请阅读http://api.jquery.com/attr/了解get attr
试试这段代码:
$(document).ready(function() {
var labels = $("#album_set-group").find("label");
labels.each(function() {
console.log($(this).attr('for'));
});
});
答案 1 :(得分:1)
您只能使用方法.attr()。在您的情况下,您可以执行类似
的操作$("#album_set-group").find("label").each(function() {
console.log($(this).attr('for'));
});
答案 2 :(得分:1)
普通JavaScript:
<label>
querySelectorAll()
收集到NodeList中
Array.prototype.slice.call()
getAttribute()
获取for
属性。push
每个for
成一个新数组。console.log(newArray)
<强>段强>
var labelList = document.querySelectorAll('label');
var labelArray = Array.prototype.slice.call(labelList);
var total = labelList.length;
var forArray = [];
for (var i = 0; i < total; i++) {
var forAttr = labelArray[i].getAttribute('for');
forArray.push(forAttr);
}
console.log('for: ' + forArray);
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<div class="inline-group" id="album_set-group">
<h2>Albums</h2>
<div class="inline-related">
<h3><b>Album:</b> <span class="inline_label">#1</span></h3>
<fieldset class="module aligned ">
<div class="form-row field-name">
<div>
<label for="id_album_set-0-name">Name:</label>
<input id="id_album_set-0-name" maxlength="100" name="album_set-0-name" type="text">
</div>
</div>
<div class="form-row field-release_date">
<div class="date-field">
<label for="id_album_set-0-release_date">Release date:</label>
<input id="id_album_set-0-release_date" name="album_set-0-release_date" type="text">
</div>
</div>
</fieldset>
</div>
</div>