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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:19:19  来源:igfitidea点击:

How to get element value in jQuery

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 litag?

您想要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

You can do the same by using jQuery on().

你可以通过使用 jQuery on()来做同样的事情。

$("#list").on('click','li',(function() {
    var selected = $(this).text();   //or .html()
    alert(selected);
})

回答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);
});