我正在 try catch 页面上成对文本框的值。
我正在捕获它们,但它并不完全按照我想要的方式工作,因为我收到了重复的数据。
这是我的 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>
这是 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);
});
});
标题:谷歌
网址:谷歌
标题:www.google.com
网址:www.google.com
标题:雅虎
网址:雅虎
标题:www.yahoo.com
网址:www.yahoo.com
最佳答案
您获得重复的数据,因为您正在迭代每个输入,然后将相同的值存储在两个变量中:
var title = $(this).attr("value");
var url = $(this).attr("value"); // same thing
您的变量 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);
});
fiddle :http://jsfiddle.net/zXTEC/
关于javascript - 使用 jQuery 循环从文本框获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19667437/