简体   繁体   English

jQuery 点击事件问题

[英]jQuery Click event issue

Hi i recently asked a question regarding targeting dynamically produced links and someone kindly provided me a working answer however, having looked into it in more detail, the functionality i need is slightly different.嗨,我最近问了一个关于定位动态生成链接的问题,有人好心地为我提供了一个可行的答案,但是,在更详细地研究之后,我需要的功能略有不同。

The following code toggles the highlighted class for a paragraph that corresponds to a link that's being produced by a separate function.以下代码切换突出显示的 class 段落,该段落对应于由单独的 function 生成的链接。 this is based on 3 mouse events:这是基于 3 个鼠标事件:

$("#hi-4").live("mouseover mouseleave click", function(){
    $("p#p-4").toggleClass("highlighted");
});

This works great, however i would like the highlighted class to stay if the relevant link is clicked(until another link is clicked) Currently it toggles for each event listed and doesn't stay highlighted if clicked.这很好用,但是如果单击相关链接,我希望突出显示的 class 保留(直到单击另一个链接)当前它会针对列出的每个事件进行切换,如果单击则不会保持突出显示。 I have tried creating separate functions for each event and have tried using .addClass , .removeClass ` in different combinations for each event but i cant get it to stay highlighted only when clicked.我尝试为每个事件创建单独的函数,并尝试在每个事件的不同组合中使用.addClass 、 .removeClass `,但我无法让它仅在单击时保持突出显示。 many thanks非常感谢

EDIT:编辑:

Heres a jsfiddle link http://jsfiddle.net/RVYnb/6/ to an example,thanks这是一个 jsfiddle 链接http://jsfiddle.net/RVYnb/6/到一个例子,谢谢

You mean you want the highlighting to stay on till the user clicks something else?您的意思是您希望突出显示一直持续到用户单击其他内容?

Behavior like this?这样的行为? : http://jsfiddle.net/QLEHY/1/ : http://jsfiddle.net/QLEHY/1/

<a href='#'>Para 1</a>
<a href='#'>Para 2</a>
<a href='#'>Para 3</a>

<p>Some text. Some text. Some text. Some text. Some text. </p>
<p>Some text. Some text. Some text. Some text. Some text. </p>
<p>Some text. Some text. Some text. Some text. Some text. </p>


$('a').click(function(){
   $('p.active').removeClass('active');
   $('p') .eq($(this).index()).addClass('active');
});

In the context of your code, simply removing the class before applying it should be fine.在您的代码上下文中,只需在应用之前删除 class 就可以了。

$("#hi-4").live("mouseover mouseleave click", function(){
    $('p.highlighted').remove(); //remove all the highlighted classes. 
    $("p#p-4").toggleClass("highlighted");
});

You probably want something like this:你可能想要这样的东西:

$("#hi-4").live("mouseover mouseleave", function(){
    if(!$("p#p-4").hasClass("clicked")) {
        $("p#p-4").toggleClass("highlighted");
    }
});

$("#hi-4").live("click", function() {
    $("p#p-4").addClass("clicked").addClass("highlighted");
});

$("a:not(#hi-4)").live("click", function() {
    $("p#p-4").removeClass("clicked").removeClass("highlighted");    
});

jsfiddle example jsfiddle 示例

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

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