emp*_*e29 11 javascript jquery javascript-events
我正在尝试创建杠杆jQuery的.on()(ex-live())来绑定多个事件.它适用于document.ready上存在的元素,但如果我在页面加载后动态添加第二个链接,则不会触发我的事件处理程序.
这是有道理的,因为最外面的方法遍历元素,并且doenst侦听新添加的DOM节点等.on(..)是侦听新DOM节点的东西,但需要事件名称参数,我不这样做直到我拥有DOM节点.
看起来像小鸡和鸡蛋的情况.
思考?
<a href="/foo.html" class="js-test" data-test-events="['click', 'mouseover']">Test 1</a>
<a href="/foo.html" class="js-test" data-test-events="['mouseout']">Test 2</a>
$(function() {
$('.js-test').each(function() {
var $this = $(this);
var e, events = $this.data('test-events');
for(e in events) {
$this.on(events[e], function() {
console.log("hello world!")
});
}
});
});
Run Code Online (Sandbox Code Playgroud)
更新,以下似乎也有效; $(this)似乎没有在正确的范围内.
<a href="/foo.html" class="js-test" data-test-events="click mouseover">Test 1</a>
<a href="/foo.html" class="js-test" data-test-events="mouseout">Test 2</a>
$(function() {
$('.js-test').on($(this).data('test-events'), function() {
// call third party analytics with data pulled of 'this'
});
});
Run Code Online (Sandbox Code Playgroud)
更新1:
我认为我最好的选择是为我想要支持的所有方法创建特殊的.on方法,如下所示:
$(document).on('click', '.js-test[data-test-events~="click"]' function(event) {
record(this, event);
});
$(document).on('mouseover', '.js-test[data-test-events~="mouseover"]', function(event) {
record(this, event);
});
... etc ...
Run Code Online (Sandbox Code Playgroud)
the*_*dox 15
$('a.js-test').on('click mouseover', function(event) {
// you can get event name like following
var eventName = event.type; // return mouseover/ click
console.log(eventName);
// you code
console.log('Hello, World!');
});
Run Code Online (Sandbox Code Playgroud)
如果你想要现场活动,那么:
$('body').on('click mouseover', 'a.js-test', function(event) {
// you can get event name like following
var eventName = event.type; // return mouseover/ click
console.log(eventName);
// you code
console.log('Hello, World!');
});
Run Code Online (Sandbox Code Playgroud)
根据你的上一次编辑试试这个:
$('.js-test').on($('.js-test').data('test-events'), function() {
console.log("hello world!")
});
Run Code Online (Sandbox Code Playgroud)
并用于直播活动授权
$('body').on($('.js-test').data('test-events'), '.js-test', function() {
console.log("hello world!")
});
Run Code Online (Sandbox Code Playgroud)