Jquery Onclick div,如果在内部div上单击,则带有class和alert



如果我点击"See me",它会提醒我"See me"
我可以按$('div')来做。点击……它也很好用。但我认为最好使用容器div。因为整个页面是一个长页面,如果我使用div进行onclick,函数将在我单击的任何地方运行。

<div class="directFilter">
    <div class="boxWithRightArrow seeMe">See me</div>
    <div class="boldFont filterHeader">Sort By</div>
    <div class="boxWithRightArrow borderTop bestClick">Best click</div>
    <div class="boxWithRightArrow intermediateTime">Intermediate time</div>
    <div class="boxWithRightArrow shortestTime">Shortest time</div>
    <div class="boxWithRightArrow iPreferred">I preferred</div>
</div>

$('.directFilter').click(function() {
        alert($(this).attr('class')); //alerts directFilter 
            if ( $( this ).hasClass( "seeMe" ) ) {
                alert("see me");
            } else if ($(this).hasClass("bestClick")) {
                alert("b click");
            } else if ($(this).hasClass("intermediateTime")) {
                alert("itime");
            } else if ($(this).hasClass("shortestTime")) {
                alert("s time");
            } else if ($(this).hasClass("iPreferred")) {
                alert("i pre");
            }
}
    );

JsFiddle:http://jsfiddle.net/smilyface/e2L7s/

有什么建议吗?

您可以使用event.target来识别事件的来源。然后您需要像$(event.target).html()$(event.target).text()那样使用html()或text()来获取元素的内部内容。

实时演示

$('.directFilter').click(function(event) {
        alert($(event.target).html()); //alerts directFilter 
});

如果您在每个If中都有唯一的工作要做,那么您将需要使用event.target作为条件中的源对象标识。

$(document).on('click',function(e) {
    // use this if you want limit clicks in .directFilter only
    // $(document).on('click','.directFilter',function(e)
    $this = $(e.target);
    alert($this.text())
});

http://jsfiddle.net/prollygeek/e2L7s/7/

$('.directFilter').children().click(function() {
      //  alert($(this).attr('class')); //alerts directFilter 
            if ( $( this ).hasClass( "seeMe" ) ) {
                alert("see me");
            } else if ($(this).hasClass("bestClick")) {
                alert("b click");
            } else if ($(this).hasClass("intermediateTime")) {
                alert("itime");
            } else if ($(this).hasClass("shortestTime")) {
                alert("s time");
            } else if ($(this).hasClass("iPreferred")) {
                alert("i pre");
            }
}
    );

为什么要使用这么多国际单项体育联合会?!

团队,

哪种方式最好

http://jsfiddle.net/smilyface/e2L7s/18/

$('.directFilter').click(function(event) {
        if($(event.target)....

http://jsfiddle.net/prollygeek/e2L7s/7/

$('.directFilter').children().click(function() {
if ( $( this )....

相关内容

最新更新