如果单击内部div,则Jquery Onclick div与类和警报

时间:2013-12-10 05:59:59

标签: javascript jquery class html onclick

如果我点击“看到我”,它应该提醒我'看见我' 我可以这样做$('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/

有什么建议吗?

4 个答案:

答案 0 :(得分:6)

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

<强> Live Demo

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

如果你有独特的工作要做,那么你需要在条件中使用event.target作为源对象标识。

答案 1 :(得分:3)

$(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())
});

答案 2 :(得分:2)

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");
            }
}
    );

为什么要使用这么多的IF?!

答案 3 :(得分:1)

哪种方法最好?

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 )....