javascript - 使用 jQuery 循环从文本框获取数据

标签 javascript jquery

我正在 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

您的变量 titleurl 包含相同的内容。

您可以迭代您的 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/

相关文章:

javascript - Heroku 的配置操作电缆 - 错误 localhost :3000/cable

javascript - 在客户端中包含 jquery-ui-browserify

javascript - jQuery/$ 为何既是函数又是 'prototype root'

javascript - 将 Angular Directive(指令)重构为组件

javascript - 在 Grails 的 params 属性中使用 JavaScript

javascript - 展开一个 div 以覆盖另一个 div

javascript - 检查 contenteditable div 中的元素(文本)是否已被删除

javascript - 是否有一个相当于 php get_class 函数的nodejs 来检测javascript 对象的确切类型?

javascript - 我可以向 &lt;input type ="text"preference ="silly"/> 之类的标签添加任意属性,然后在 JS 代码中访问它吗

jquery - 具有先前行跨度列的表列索引