Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在不给他们ID的情况下获取li的文本?_Javascript_Jquery_Html - Fatal编程技术网

Javascript 如何在不给他们ID的情况下获取li的文本?

Javascript 如何在不给他们ID的情况下获取li的文本?,javascript,jquery,html,Javascript,Jquery,Html,我在ul标签中有四个li标签 当我选择一个li并隐藏其他三个li值时,我希望在li标记内获取文本 页面上应仅显示选定的一个 <ul id="names"> <li>a</li> <li>b</li> <li>c</li> <li>d</li> </ul> a b c d 这回答了您问题的两个部分: $('#names li').click(function

我在
ul
标签中有四个
li
标签

当我选择一个li并隐藏其他三个li值时,我希望在li标记内获取文本

页面上应仅显示选定的一个

<ul id="names">
  <li>a</li>
  <li>b</li>
  <li>c</li>
  <li>d</li>
</ul>
  • a
  • b
  • c
  • d

这回答了您问题的两个部分:

$('#names li').click(function(){    
  var x = $(this).text(); // gets the text of the selected li
  alert(x); // displays the text inside the selected li 
  $(this).siblings().hide();​​​​ // hides all other li's   
});

这是一个适用于您的示例的示例。

这回答了您问题的两个部分:

$('#names li').click(function(){    
  var x = $(this).text(); // gets the text of the selected li
  alert(x); // displays the text inside the selected li 
  $(this).siblings().hide();​​​​ // hides all other li's   
});
$('#names li').click(function(){
    $(this).siblings().hide();
});
下面是一个适用于您的示例的示例。

尝试这样做

$('#names li').click(function(){
    $(this).siblings().hide();
});
$("#names li").click(function(){
   var selected = $(this);
   alert('You have selected '+ $(this).text());
   $("#names li").hide();
   $(this).show();
});
检查小提琴

像这样试试

$("#names li").click(function(){
   var selected = $(this);
   alert('You have selected '+ $(this).text());
   $("#names li").hide();
   $(this).show();
});

检查小提琴这个怎么样?它将隐藏它们并显示使用jQuery选择器单击的一个

$('#names li').click(function() {
    $('#names li').hide();
    $(this).show();
})

使用示例:

这个怎么样?它将隐藏它们并显示使用jQuery选择器单击的一个

$('#names li').click(function() {
    $('#names li').hide();
    $(this).show();
})

用法示例:

if条件将始终为true,因为$(this)将始终返回一个新对象,该对象永远不会等于所选引用的对象…if条件将始终为true,因为$(this)将始终返回一个新对象,该对象永远不会等于所选引用的对象…val()我看不到课文。我认为应该是
.text()
,如上面的答案所示。@MayuMayooresan已更改。我的答案似乎是唯一一个回答整个问题的答案。val()无法理解文本。我认为应该是
.text()
,如上面的答案所示。@MayuMayooresan已更改。我的答案似乎是唯一一个回答整个问题的答案。