Как иметь событие click только огонь на родительском DIV, а не дети?
У меня есть DIV с классом foobar, и через несколько ДИВС внутри, что div, который является неклассным, но я предполагаю, что они наследуют foobar класс:
$('.foobar').on('click', function() { /*...do stuff...*/ });
Я хочу, чтобы стрелять только при нажатии где-то в DIV, но не на его дочерних Дивов.
6 ответов:
если
e.targetЭто тот же элемент, что иthis, вы не нажали на потомка.$('.foobar').on('click', function(e) { if (e.target !== this) return; alert( 'clicked the foobar' ); });.foobar { padding: 20px; background: yellow; } span { background: blue; color: white; padding: 8px; }<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class='foobar'> .foobar (alert) <span>child (no alert)</span> </div>
есть еще один способ, который работает, если вы не возражаете только против более новые браузеры. Просто добавьте CSS
pointer-events: none;для любых дочерних элементов div, которые вы хотите захватить щелчок. Вот таблицы поддержки
вы можете использовать пузырение в свою пользу:
$('.foobar').on('click', function(e) { // do your thing. }).on('click', 'div', function(e) { // clicked on descendant div e.stopPropagation(); });
//bind `click` event handler to the `.foobar` element(s) to do work, //then find the children of all the `.foobar` element(s) //and bind a `click` event handler to them that stops the propagation of the event $('.foobar').on('click', function () { ... }).children().on('click', function (event) { event.stopPropagation(); //you can also use `return false;` which is the same as `event.preventDefault()` and `event.stopPropagation()` all in one (in a jQuery event handler) });это остановит распространение (пузырение)
clickсобытие на любом из дочерних элементов.foobarэлемент(ы), так что событие не достигнет.foobarэлемент(ы), чтобы запустить их обработчик(ы) событий.вот демо:http://jsfiddle.net/bQQJP/
$(".advanced ul li").live('click',function(e){ if(e.target != this) return; //code // this code will execute only when you click to li and not to a child })
У меня была та же проблема, и я придумал это решение (на основе других ответов)
$( ".newsletter_background" ).click(function(e) { if (e.target == this) { $(".newsletter_background").hide(); } });в основном он говорит, что если целью является div, то запустите код, иначе ничего не делайте (не скрывайте его)
Comments