jQuery onFailure()
和.on()
方法提供了一种方法,通过指定" event.namespace"来绑定和触发单个元素上的多个处理程序,而不会互相干扰。
但是,我发现命名空间不适用于.trigger()
,它只会触发连接在不同命名空间中的所有绑定处理程序。
代码非常简单,例如:
checkbox
$('input[type="checkbox"]').on('click.n1',func1).on('click.n2',func2);
$('input[type="checkbox"]').trigger('click.n1');
和func1
都会被解雇。
相同的代码在其他元素上运行良好。
这是一个错误吗?或者我错过了复选框的内容?
func2

$("#myCheckbox")
.on('click.checks1',function(e){console.log('click.checks1 fired, the namespace is: '+e.namespace)})
.on('click.checks2',function(e){console.log('click.checks2 fired, the namespace is: '+e.namespace)});
$("#myCheckbox").trigger('click.checks1');
$("#myRadio")
.on('click.radios1',function(e){console.log('click.radios1 fired, the namespace is: '+e.namespace)})
.on('click.radios2',function(e){console.log('click.radios2 fired, the namespace is: '+e.namespace)});
$("#myRadio").trigger('click.radios1');

答案 0 :(得分:0)
你的选择器错了。
$('checkbox').on('click.n1',func1).on('click.n2',func2);
应该是
$('input[type="checkbox"]').on('click.n1',func1).on('click.n2',func2);
这是一个小例子,可以使这个工作,虽然我不知道它是否真的会帮助你,因为你没有解释你想要做什么。
$('input[type="checkbox"]').on('test.n1',function (e) {
console.log(e.namespace);
});
$('input[type="radio"]').click(function(e) {
$('input[type="checkbox"]').trigger('test.n1');
});
因此,在现有代码中,每次单击单选按钮时都会触发复选框。
官方jquery api https://api.jquery.com/event.namespace/
中的更多信息答案 1 :(得分:0)
问题在于:
$("#checks input")
.on('click.checks1',function(){console.log('click.checks1')})
.on('click.checks2',function(){console.log('click.checks2')});
为所有#checks input
定义两个事件。所以每次点击1都会被解雇。
可能重复:Custom namespaced events will not work
来自there:
它们不是等级的;只需要一个名称匹配
所以基本上“点击”事件触发“点击”事件,“click.checks1”事件和“click.checks2”事件导致只需要匹配一个名称。
编辑:
正如您在下面的代码段中看到的那样,复选框会调用click
事件,然后这会引发两个事件。
Radiobutton不会调用click
事件,只调用您定义的命名空间的事件。
此外,您可以看到e.handleObj.namespace
也有复选框的值。
这似乎是一个错误。
$("#myCheckbox").on('click', function (e) {console.warn('DEFAULT CHECKBOX')});
$("#myRadio").on('click', function (e) {console.warn('DEFAULT RADIO')});
$("#myCheckbox")
.on('click.checks1',function(e){console.log('click.checks1 fired, the namespace is: '+e.namespace+ ' HandleObj NameSpace '+e.handleObj.namespace )})
.on('click.checks2',function(e){console.log('click.checks2 fired, the namespace is: '+e.namespace+ ' HandleObj NameSpace '+e.handleObj.namespace)});
$("#myCheckbox").trigger('click.checks1');
$("#myRadio")
.on('click.radios1',function(e){console.log('click.radios1 fired, the namespace is: '+e.namespace+ ' HandleObj NameSpace '+e.handleObj.namespace)})
.on('click.radios2',function(e){console.log('click.radios2 fired, the namespace is: '+e.namespace+ ' HandleObj NameSpace '+e.handleObj.namespace)});
$("#myRadio").trigger('click.radios1');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='checkbox' id='myCheckbox' />
<input type='radio' id='myRadio' />