我正在尝试捕获页面上的文本框对的值.
我正在捕捉它们,但它并没有按照我想要的方式工作,因为我正在获取重复数据.
这是我的HTML代码:
<div id="links">
<div id="group1">
<input type="text" name="linkTitle" value="Google">
<input type="text" name="linkURL" value="www.google.com">
</div>
<div id="group2">
<input type="text" name="linkTitle" value="Yahoo">
<input type="text" name="linkURL" value="www.Yahoo.com">
</div>
</div>
<div>
<input id="btnSaveLinks" type="button" value="Save">
</div>
Run Code Online (Sandbox Code Playgroud)
这是javascript:
$("#btnSaveLinks").on('click', function() {
$('#links input[type=text]').each(function () {
var title = $(this).attr("value");
var url = $(this).attr("value");
console.log('title: ' + title);
console.log('url: ' + url);
});
});
Run Code Online (Sandbox Code Playgroud)
标题:谷歌
网址:谷歌
标题:www.google.com
网址:www.google.com
标题:雅虎
网址:雅虎
标题:www.yahoo.com
网址:www.yahoo.com
您正在获取重复数据,因为您正在迭代每个输入,然后在两个变量中存储相同的值:
var title = $(this).attr("value");
var url = $(this).attr("value"); // same thing
Run Code Online (Sandbox Code Playgroud)
你的变量title和url包含相同的东西.
您可以遍历div,然后获取其中的输入:
$('#links div').each(function() {
var title = $(this).find('[name=linkTitle]').val();
var url = $(this).find('[name=linkURL]').val();
console.log('title: ' + title);
console.log('url: ' + url);
});
Run Code Online (Sandbox Code Playgroud)
小提琴:http://jsfiddle.net/zXTEC/