jQuery 如何在jQuery中获取元素值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/551538/
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 element value in jQuery
提问by zsharp
Why is it not returning value in 'li'? What am i doing wrong?
为什么它不在'li'中返回值?我究竟做错了什么?
$("#list li").click(function() {
var selected = $(this).val();
alert(selected);
})
回答by Jason Cohen
Did you want the HTML or text that is inside the li
tag?
您想要li
标签内的 HTML 或文本吗?
If so, use either:
如果是这样,请使用:
$(this).html()
or:
或者:
$(this).text()
The val()
is for form fields only.
该val()
是唯一的表单字段。
回答by Daxon
<ul id="unOrderedList">
<li value="2">Whatever</li>
.
.
$('#unOrderedList li').click(function(){
var value = $(this).attr('value');
alert(value);
});
Your looking for the attribute "value" inside the "li" tag
您在“li”标签内寻找属性“value”
回答by Mark Hurd
Use .text() or .html()
使用 .text() 或 .html()
$("#list li").click(function() {
var selected = $(this).text();
alert(selected);
});
回答by svinto
A li doesn't have a value. Only form-related elements such as input, textarea and select have values.
一个 li 没有价值。只有与表单相关的元素,例如 input、textarea 和 select 才有值。
回答by Andreas Grech
Most probably, you want something like this:
最有可能的是,你想要这样的东西:
$("#list li").click(function() {
var selected = $(this).html();
alert(selected);
});
回答by fanick
<div class="inter">
<p>Liste des Produits</p>
<ul>
<li><a href="#1">P1</a></li>
<li><a href="#2">P2</a></li>
<li><a href="#3">P3</a></li>
</ul>
</div>
$(document).ready(function(){
$(".inter li").bind(
"click", function(){
alert($(this).children("a").text());
});
});
回答by Mr_Green
回答by Itisha-systematix
To get value of li we should use $("#list li").click(function() { var selected = $(this).html();
要获取 li 的值,我们应该使用 $("#list li").click(function() { var selected = $(this).html();
or
或者
var selected = $(this).text();
alert(selected);
})
})
回答by harry
$("#list li").click(function() {
var selected = $(this).html();
alert(selected);
});