jQuery 如何访问ul标签中的li元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17982861/
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 20:19:21  来源:igfitidea点击:

How to access li elements within ul tag

javascriptjqueryhtmlcss

提问by De Vonte

I want to know how to access each li within the ul? I am not sure exactly what the name of the ul is.

我想知道如何访问 ul 中的每个 li?我不确定 ul 的确切名称是什么。

Here is the code:

这是代码:

<ul class= "selectBox-options exp-pdp-size-dropdown exp-pdp-dropdown" style>
    <li class = " omitted">
        more li here omitted
 </ul>

My main goal is to have a user click a size in a dropdown lets say size 8 and it will automatically detect that specific li(8) inside the ul

我的主要目标是让用户点击下拉菜单中的尺寸,比如尺寸 8,它会自动检测 ul 中的特定 li(8)

回答by Brilliand

You could use querySelectorAll:

你可以使用querySelectorAll

var array_of_li =  document.querySelectorAll("ul.selectBox-options li");

If you're not sure that the ulwill have the selectBox-optionsclass, then delete the .selectBox-optionspart - but remember that it will get you every lion the page then.

如果您不确定该类是否ul会包含selectBox-options该类,请删除该.selectBox-options部分 - 但请记住,它会li在页面上显示所有内容。

If you're using jQuery, then this is a bit more compatible, and does basically the same thing:

如果您使用的是 jQuery,那么这会更兼容一些,并且基本上做同样的事情:

var li =  $("ul.selectBox-options li");

回答by Jonast92

If you accept jQuery, like you mentioned:

如果你接受 jQuery,就像你提到的:

$( "li" ).each(function( index ) {
    console.log( index + ": " + $(this).text() );
});

As the jQuery documentationdeclares.

正如 jQuerydocumentation声明的那样。

I'm not sure how to do it with raw javascript though :)

不过,我不确定如何使用原始 javascript 做到这一点:)

回答by Repeat Spacer

in CSS:

在 CSS 中:

li { color:black; }

with ul:

与 ul:

ul li { }

or with class:

或与班级:

ul li.ommitted { }

or with ul&li class

或使用 ul&li 类

ul.selectBox-options li.ommitted { }

ps. Don't forget the end tag

附:不要忘记结束标签

</li>

回答by Shylo Hana

<html>
  <head>

    <style type='text/css'>
      .omitted {
        color:                  rgb(0, 0, 0);
        background:             transparent;
      }

      .selected {
        color:                  rgb(255, 255, 255);
        background:             rgb(0, 0, 0);
      }
    </style>

    <script type='text/javascript'>
      function matchSelected(foo) {
        var selectBox =         document.getElementById('selectBox');
        var items =             selectBox.getElementsByTagName('LI');

        for(i=0; i<items.length; i++) {
          items[i].className =  items[i].innerHTML == foo ? 'selected' : 'ommitted';
        }
      }
    </script>

  </head>


  <body>


    <ul id='selectBox' class='selectBox-options exp-pdp-size-dropdown exp-pdp-dropdown'>
      <li class='omitted'>1</li>
      <li class='omitted'>3</li>
      <li class='omitted'>8</li>
      <li class='omitted'>10</li>
      <li class='omitted'>14</li>
    </ul>


    <select onChange='matchSelected(this.value);'>
      <option value='1'>One</option>
      <option value='3'>Three</option>
      <option value='8'>Eight</option>
      <option value='10'>Ten</option>
      <option value='14'>Fourteen</option>
    </select>


  </body>
</html>

回答by yeyene

You want like this? DEMO http://jsfiddle.net/yeyene/ZjHay/

你想要这样吗?演示http://jsfiddle.net/yeyene/ZjHay/

$(document).ready(function(){
    $('select').on('change',function(){
        alert($('.selectBox-options li').eq($(this).val()-1).text());
    });
});

回答by ojrask

If the selectand the ulare siblings inside the same parent element (a divfor instance), you can use querySelectorand querySelectorAllto select the proper ulelement and its children.

如果selectul是同一个父元素内的兄弟元素(div例如 a),您可以使用querySelectorquerySelectorAll来选择适当的ul元素及其子元素。

HTML

HTML

<div id="container">

    <select>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
    </select>

    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
        <li>Item 4</li>
    </ul>

</div>

JavaScript

JavaScript

var select = document.querySelector( "#container > select" );
var ul_children = ul_list.querySelectorAll( "#container > select ~ ul > li" );
var selected_li = undefined; // Undefined for now, see below for setting its value.

// If we got results for both select and ul_children.
if ( select !== null && ul_children.length > 0 )
{
    // Map function to the select's "change" event to pick a correct list item.
    select.addEventListener( "change", function( event )
    {
        // Get the select's value after changing the option.
        var selected = select.value;

        // Decrement with 1 to fix offset (ul_children starts from 0).
        selected--;

        // use the select's value to choose the right list item from the li collection.
        selected_li = ul_children.childNodes[ selected ];
    });
}

(Above code is probably not cross-browser compatible out of the box, remember to use working code.)

(以上代码可能不是开箱即用的跨浏览器兼容,请记住使用工作代码。)

In the above code, we first get the selectelement and the ul's child elements (lis). Then we map an anonymous function (could be named too) to the selects changeevent (which is triggered each time an option is chosen with it). This function then selects the proper liitem from the item collection we fetched in line two and assign it to a variable called selected_li.

在上面的代码中,我们首先获取select元素和ul的子元素(lis)。然后我们将一个匿名函数(也可以命名)映射到selectschange事件(每次选择一个选项时都会触发该事件)。然后,此函数li从我们在第二行获取的项目集合中选择合适的项目,并将其分配给名为 的变量selected_li

Now you can manipulate and use the selected_lihowever you want.

现在您可以随意操作和使用selected_li

EDIT: with jQuery this job is probably a bit easier.

编辑:使用 jQuery,这项工作可能会更容易一些。