简体   繁体   English

我没有使用jul获得ul li的值

[英]I dont get value of li of ul using jquery

I want to get the value of li of ul using jQuery. 我想使用jQuery获取ul li的值。 Now i got null value. 现在我得到空值。 Can anybody give any suggestion? 有人可以提出任何建议吗?

<ul>
    <li id="1" onClick="page()">1</li>
    <li id="2" onClick="page()">1</li>
</ul>

<script>
    function page() {
        var sss = $(this).html();
        alert(sss);
    }
</script>

You need to pass this to the function: 您需要this传递给函数:

<ul>
    <li id="1" onClick="page(this)">1</li>
    <li id="2" onClick="page(this)">1</li>
</ul>
function page(el) {
    var sss = $(el).html();
    alert(sss);
}

Or alternatively (and preferably) you can use jQuery itself to attach your events: 或者,(最好是)您可以使用jQuery本身来附加事件:

<ul>
    <li id="1">1</li>
    <li id="2">1</li>
</ul>
$('li').click(function() {
    var sss = $(this).html();
    alert(sss);
});

You need to pass the current clicked element object: 您需要传递当前单击的元素对象:

DOM: DOM:

<ul>
 <li id="1" onClick="page(this)">1</li>
 <li id="2" onClick="page(this)">1</li>
</ul>

JS: JS:

function page(obj)
{
 var sss=$(obj).html();
 alert(sss);
}

Working Demo 工作演示

<ul id="theList">
    <li>1</li>
    <li>2</li>
</ul>

<script>
$(function(){
    $('#theList li').click(function(){
        alert($(this).html());
    });
});
</script>

For a more jquery contained approach 对于更多的jQuery包含的方法

Don't mix jQuery with attribute-based onclick handlers. 请勿将jQuery与基于属性的onclick处理程序混合使用。 You separate the event handler from the event registration for no benefit (makes it harder to maintain the page). 您将事件处理程序与事件注册分开是毫无用处的(这使得维护页面更加困难)。 The jQuery way also supports multiple handlers, even for the same event, on the same elements. jQuery方式还支持在同一元素上的多个处理程序,即使对于同一事件也是如此。

Just do it this way: 就是这样:

<li id="1">1</li>
<li id="2">2</li>

and the code becomes 然后代码变成

$('li').click(function(){
   var sss = $(this).html();
    alert(html)
});

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

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