2013-12-12 92 views
1

我想从隐藏字段获取值。我正在使用代码jquery无法从隐藏字段获取值

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

我得到的答案只是该句的第一个单词。 值是一个很大的句子我在一个函数foo中使用上面的代码,并且这个函数foo在ajax调用中的一个附加函数内被调用。

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

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

难道我做错了

+0

你会写完整的代码和HTML。 –

+0

嗨乔治,这将是有用的,你有一个看法,你的HTML代码,看看你的js应该做什么。你说的只是从整个句子中只取出一个单词,但在你的例子中没有。 – mamoo

+0

输入错误我在我的原始代码 – George

回答

2

你还没有给定id idhere到元素。

尝试:

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

嘛,哪里是 “#idhere”?
没有分配此ID的元素!

2

我想你错过了ID的隐藏字段

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

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