1

我已经看到这两种将点击事件绑定到元素的不同方式,但我不明白其中的区别。

$('#cool-thing').on('click', function() {
  alert('This works!');
});

$(document).on('click', '#cool-thing', function() {
  alert('This works!');
});

当元素被单击时,它们都会产生警报#cool-thing,那么两者之间是否存在显着差异,或者只是做同一件事的不同方式?

4

2 回答 2

2

第二个选项是事件委托,在附加事件时#cool-thing可能不存在DOM,但可以document 在当前浏览会话期间动态附加。#cool-thing也可以使用父元素。

第一个选项是#cool-thing存在于DOM.

于 2016-01-22T03:30:49.613 回答
0

感谢那些回答我问题的人。两个答案都非常有帮助。

为了帮助自己理解您的答案,我在小提琴中玩弄这个。我想我也会分享 Fiddle 作为答案,希望能帮助其他人理解这一点,以防你像我一样,只能通过视觉示例来学习。

https://jsfiddle.net/zf3g22um/2/

HTML

<button id="add-reg-bound-element">Add Regularly-Bound Element</button>
<button id="add-doc-bound-element">Add Document-Bound Element</button>

CSS

.reg-bound-element, .doc-bound-element {
  font: 600 14px sans-serif;
  height: 100px;
  line-height: 100px;
  text-align: center;
  width: 300px;
}

.reg-bound-element {
  background-color: #BBB;

  &:before {
    content: 'Regularly-Bound Element';
  }
}

.doc-bound-element {
  background-color: green;
  color: white;

  &:before {
    content: 'Document-Bound Element';
  }
}

JS

//////////////////////////
// REGULARLY BOUND ELEMENT
//////////////////////////
$('#add-reg-bound-element').on('click', function() {
  $('html').append('<div class="reg-bound-element"></div>');
});

$('.reg-bound-element').on('click', function() {
  alert('Regular binding works!');
});

/////////////////////////
// DOCUMENT BOUND ELEMENT
/////////////////////////
$('#add-doc-bound-element').on('click', function() {
  $('html').append('<div class="doc-bound-element"></div>');
});

$(document).on('click', '.doc-bound-element', function() {
  alert('Document binding works!');
});
于 2016-01-22T18:09:32.920 回答