繁体   English   中英

jQuery无法从隐藏字段中获取价值

[英]jquery not able to get value from a hidden field

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

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

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

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

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

我做错了吗

好吧,“#idhere”在哪里?
没有分配此ID的元素!

您尚未将id idhere赋予此元素。

尝试:

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

我想你想念隐藏字段中的ID

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM