简体   繁体   English

jQuery和onclick在这种情况下不起作用

[英]JQuery and onclick doesn't work in this context

striving to make jquery and li working in this context: 努力使jquery和li在这种情况下工作:

<div id="statLateralMenu">
    <h3>Statistics</h3>

    <ul>
        <li id="id1" class="selected">Stat 1</li>
        <li id="id2">Stat 2</li>
    </ul>
</div>

s s

$(function() {
    $("#statLateralMenu li").click(function()
    {
        alert( "A" );
        $("#statLateralMenu li").removeClass("selected");
        $(this).addClass("selected");
    });
}
);

I am pretty sure the error is very stupid also because I've already implemented this code in another area of my page and it works perfectly, but this time really I can't make it working. 我很确定该错误也是非常愚蠢的,这是因为我已经在页面的另一个区域中实现了此代码,并且可以正常工作,但是这次确实无法使其正常工作。 Any clue please? 有什么线索吗?

EDIT: 编辑:

I am not able even to fire the alert, my problem is not (yet) to change the class's li . 我不能连火警报,我的问题是,(还)没有改变类的li JQuery is loaded as in the same page I have another ul/li complex and it works perfectly jQuery在同一页面中加载,因为我有另一个ul / li复合体,它运行完美

EDIT 2: At this point maybe I am messing up a bit, but using my code here it doesn't work as well: https://jsfiddle.net/nakjyyaj/4/ 编辑2:在这一点上也许我有点混乱,但在这里使用我的代码也无法正常工作: https : //jsfiddle.net/nakjyyaj/4/

It seems to work : 似乎有效:

 $(function() { $("li").click(function() { $("li").removeClass("selected"); $(this).addClass("selected"); }); }); 
 .selected{background:yellow} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li>azerty</li> <li>bzerty</li> <li>czerty</li> </ul> 

To deal with dynamic content you can use event delegation : 要处理动态内容,可以使用事件委托:

 $(function() { $("ul").on("click", "li", function() { $("li").removeClass("selected"); $(this).addClass("selected"); }); }); setTimeout(function () { $("p").remove(); $("ul").html("" + "<li>azerty</li>" + "<li>bzerty</li>" + "<li>czerty</li>" ); }, 1000); 
 .selected{background:yellow} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>Wait 1 second.</p> <ul></ul> 

Further reading : https://stackoverflow.com/a/46251110/1636522 . 进一步阅读: https//stackoverflow.com/a/46251110/1636522

try to change $("#statLateralMenu li").removeClass("selected"); 尝试更改$("#statLateralMenu li").removeClass("selected"); to

$(this).removeClass("selected");

like that 像那样

$(function() {
    $("#statLateralMenu li").click(function()
    {
        alert( "A" );
        $(this).removeClass("selected");
        $(this).addClass("selected");
    });
}
);

but if you want only to change design elements you can use :hover 但是,如果您只想更改设计元素,则可以使用:hover

li:hover { 
    background-color: yellow;
}

In your JSFiddle, you forgot to load JQuery framework. 在您的JSFiddle中,您忘记了加载JQuery框架。 You don't need script tag in JSFiddle (no need and ). 您不需要JSFiddle中的脚本标签(不需要和)。

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

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