如何使用 JavaScript 获取文本字段的值?(jQuery)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4905906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get value of a text field using JavaScript? (jQuery)
提问by Zabba
I'm trying to get the value of a text field using jQuery, but it is not working.
我正在尝试使用 jQuery 获取文本字段的值,但它不起作用。
Below is the test:
下面是测试:
I have this in HTML:
我在 HTML 中有这个:
<input type="text" id="user_time_zone_offset_hours" name="user_time_zone_offset_hours" value="7"/>
In JavaScript, using jQuery(this does not work):
在 JavaScript 中,使用 jQuery(这不起作用):
alert($('#user_time_zone_offset_hours').value); //Result is 'undefined'
In JavaScript, not using jQuery(this works):
在 JavaScript 中,不使用 jQuery(这有效):
alert(document.getElementById("user_time_zone_offset_hours").value); //Result is 7
Why is jQuery returning 'undefined' ?
为什么 jQuery 返回 'undefined' ?
回答by David Tang
jQuery wraps the original DOM objects in its own object, so the .value
property isn't directly accessible.
jQuery 将原始 DOM 对象包装在它自己的对象中,因此.value
无法直接访问该属性。
To get the original DOM object, you can access the jQuery object as an array:
要获取原始 DOM 对象,您可以将 jQuery 对象作为数组访问:
$('#user_time_zone_offset_hours')[0].value;
Alternatively, jQuery provides a method to get inputs' values:
或者,jQuery 提供了一种获取输入值的方法:
$('#user_time_zone_offset_hours').val();
回答by JasCav
It doesn't work because .value isn't the correct call. Try using the .val() function.
它不起作用,因为 .value 不是正确的调用。尝试使用.val() 函数。
alert($('#user_time_zone_offset_hours').val());
回答by sevenseacat
Try $('#user_time_zone_offset_hours').val()
.
试试$('#user_time_zone_offset_hours').val()
。
回答by Jakub Arnold
To get the value try
要获得价值尝试
$('#user_time_zone_offset_hours').val()
you can also use
你也可以使用
$('p').text()
to get the inner text of a paragraph element, or
获取段落元素的内部文本,或
$('#any_div').html()
to get HTML contents of any element.
获取任何元素的 HTML 内容。
The difference between text()
and html()
is that if you use text()
to set HTML content, eg.
text()
和之间的区别在于html()
,如果您用于text()
设置 HTML 内容,例如。
$("#and_div").text('<a href="example.com">Link</a>');
it will get escaped
它会逃脱
<a href="example.com">Link</a>
回答by Pradeep
You can use $('#user_time_zone_offset_hours').html()
.
您可以使用$('#user_time_zone_offset_hours').html()
.