【问题标题】:jquery not able to get value from a hidden fieldjquery 无法从隐藏字段中获取值
【发布时间】:2013-12-30 12:01:53
【问题描述】:

我正在尝试从隐藏字段中获取值。我正在使用代码

function foo(){
 alert($('#idhere').val());
}

我得到的答案只是那句话的第一个词。 该值是一个大句子我在函数 foo 中使用上面的代码,并且在 ajax 调用中的 append 函数中调用了这个函数 foo。

$.each(data, function(i, item) {
 $("#news").append('<a onclick="foo()">xxx</a><input type="hidden" id="idhere" value="item[0]"');
}

为什么我只收到一个单词作为警报。

我做错了吗

【问题讨论】:

  • 能不能写完整的代码和html。
  • 嗨,George,查看您的 html 代码以了解您的 js 应该做什么会很有用。您谈到只从整个句子中提取一个词,但在您的示例中没有一个词可见。
  • 我的原始代码中有输入错误
  • @GeorgeK 您有许多具有相同 ID 的输入!看我的回答!
  • @Tony 让我检查一下...

标签: javascript jquery ajax append


【解决方案1】:

ID 应该是唯一的!您使用 $.each,这意味着您可能会创建许多具有相同 id 的元素。这很糟糕。

$.each(data, function(i, item) {
    $("#news").append('<a onclick="foo()">xxx</a><input type="hidden" id="idhere' + i + '"    value="item[0]"');
}

用途:

function foo(){
  alert($('#idhere0').val());
}

或者:

var vals = $.map($('input[type="hidden"]'), function(el) {
    return $(el).val();
});
alert(vals.join('\n'));

【讨论】:

    【解决方案2】:

    我想你错过了隐藏字段中的 id

    $("#news").append('<a onclick="foo()">xxx</a><input type="hidden" value="item[0]" id="idhere"');
    

    【讨论】:

      【解决方案3】:

      那么,“#idhere”在哪里?
      没有分配此 id 的元素!

      【讨论】:

        【解决方案4】:

        你还没有给元素 id idhere

        试试:

        $("#news").append('<a onclick="foo()">xxx</a><input type="hidden" value="item[0]" id="idhere"');
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-03-12
          • 2011-03-06
          • 1970-01-01
          • 1970-01-01
          • 2014-04-10
          • 2012-01-28
          • 1970-01-01
          • 2010-11-03
          相关资源
          最近更新 更多