简体   繁体   English

如何嵌套 <li> 标签值

[英]how to get nested <li> tag value

I need to get the value "B" . 我需要获取值"B" But coming with value "A" . 但是带有值"A" I do not to get the value of "A". 我没有得到“ A”的值。 How to distinguish? 如何区分?

My HTML structure: 我的HTML结构:

 <li> <ul> <li value="A"> <ul> <li onclick="cick(this)" value="B"></li> </ul> </li> </ul> </li> 

If you want to get the value of a particular <li> element when there are more than one in the document, you can distinguish between the element by using unique id s or class es. 如果要在文档中有多个<li>元素时获取特定<li>元素的值,则可以使用唯一的idclass来区分该元素。

Option 1: IDs 选项1:ID

<li>
   <ul>
      <li id="number1" value="100">
         <ul>
             <li id="number2" onclick="click(this)" value="200"></li>
         </ul>
      </li>
   </ul>
</li>

To get the value you would then: 要获得价值,您将:

function(){
  var el = document.getElementById("number2")
  var value = el.value; // outputs 200
}

Option 2: Classes 选项2:课程

<li>
   <ul>
      <li class="number1" value="150">
         <ul>
             <li class="number2" onclick="click(this)" value="300"></li>
         </ul>
      </li>
   </ul>
</li>
function(){
  var el = document.getElementsByClassName("number2")[0]
  var value = el.value; // outputs 300
}

List items can't have non-numeric values. 列表项不能包含非数字值。 For your HTML to be considered valid, you'll need to change your values to numbers. 为了使您的HTML有效,您需要将值更改为数字。 If you do this, you can then easily use javascript to get your values. 如果执行此操作,则可以轻松使用javascript获取值。 A HTML structure with valid values may look something like so: 具有有效值的HTML结构可能如下所示:

<li>
   <ul>
      <li value="1"> <!-- Changed A to 1 -->
         <ul>
             <li onclick="cick(this)" value="2"></li> <!-- Changed B to 2 -->
         </ul>
      </li>
   </ul>
</li>

You can use document.querySelector and pass in the selector li[value="1"] > ul > li (this will select all li tags which are a child of a ul tag which is a child of a li tag with the value of 1 ). 您可以使用document.querySelector并传入选择器li[value="1"] > ul > li (这将选择所有li标签的子标签,这些标签是ul标签的子标签,而ul标签的子标签是li标签的子标签,其值为1 )。 You can use this generically for a parent list item of value x like so: 您可以将其通常用于值x的父列表项,如下所示:

li[value="x"] > ul > li

See example below: 请参见下面的示例:

 const val = document.querySelector('li[value="1"] > ul > li').value; console.log(val); // 2 
 <li> <ul> <li value="1"> <ul> <li id="A" onclick="cick(this)" value="2"></li> </ul> </li> </ul> </li> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM