【问题标题】:getting data from textboxes using a jQuery loop使用 jQuery 循环从文本框中获取数据
【发布时间】:2013-11-09 03:38:57
【问题描述】:

我正在尝试在我的页面上捕获文本框对的值。

我正在捕获它们,但它并没有完全按照我想要的方式工作,因为我正在获取重复数据。

这是我的 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

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    您会得到重复的数据,因为您正在迭代每个输入,然后将相同的值存储在两个变量中:

    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);
    });
    

    小提琴:http://jsfiddle.net/zXTEC/

    【讨论】:

      【解决方案2】:

      这是重复的,因为您使用此行 $(this).attr("value"); 为每个文本框写入值两次两个不同的变量...

      【讨论】:

        猜你喜欢
        • 2016-11-17
        • 1970-01-01
        • 1970-01-01
        • 2014-03-26
        • 1970-01-01
        • 1970-01-01
        • 2016-04-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多