Запустите JavaScript на Btn, но не контейнер

0

У меня есть это: http://jsfiddle.net/G3VjC/

что просто:

$(document).ready(function() {

$(document).on('click','#btn',function(){
    console.log('ran btn');
});
$(document).on('click','#containerdiv',function(){
    console.log('ran div');
});

});

Но при нажатии кнопки запускается команда btn JS и контейнер JS (см. Консольный журнал).

Как я могу отделить их?

благодаря

Теги:

4 ответа

4
Лучший ответ

use stopPropagation()

$(document).on('click','.meee',function(e){ // add event as argument
    console.log('ran btn');
    e.stopPropagation()
});
  • 0
    Благодарю. Это сработало.
1

Попробуй это

$(document).ready(function() {
    $(document).on('click','#containerdiv',function(){
        console.log('ran div');

    });

    $(document).on('click','.meee',function(){
        console.log('ran btn');
        return false;
    });
});

демонстрация

0
$(document).on('click','#btn',function(e){
e.stoppropagation();
var target = $(e.target);
if(!target.attr('id') == 'btn'){
 e.preventDefault();
 $(target.find("#btn)).trigger("click")
}
//any additional logic if the target was of the intended type.
});
0

Или попробуйте следующее:

$(document).ready(function() {
    $('#containerdiv').click(function(){
        console.log('ran div');
    });

   $('.meee').click(function(e){
           e.stopPropagation();
           console.log('ran btn');
   });
});

Как сказал chumkiu, просто используйте stopPropagation()

Ещё вопросы

Сообщество Overcoder
Наверх
Меню