运行Child's Onclick,但不要运行Parent's Where参数被传递
Run Child's Onclick But Not Parent's Where Argument is Passed
给出一些简单的HTML,其中一个元素有一个onclick
函数,它的子元素也有一个onclick
函数:
<div style='background-color:blue;width:500px;height:500px;'
onclick='thing1();'>
<div style='background-color:red;width:100px;height:100px;'
onclick='thing2(57);'></div>
</div>
什么是正确的方法,以便当用户单击子元素时,只有子元素的onclick
被执行,而不是父元素的,但是当父元素被单击时,它的onclick
仍然被执行?我看到event.stopPropagation()
将是正确的方式去,但是因为我传递一个参数给函数thing2()
,我似乎不能传递事件。例如:
function thing2(a,ev) {
// Do something with a
ev.stopPropagation();
}
不能工作,错误为TypeError: ev is undefined
.
事件是第一个参数
function thing2(ev) {
var a = ev.target
ev.stopPropagation()
}
其次,最好不要使用onclick=
。相反,给你的div类或id,并做这样的事情:
<div class="thing-1" data-thingy="57">
<div class="thing-2" data-thingy="65"></div>
</div>
<script>
$('.thing-1').click(function (ev) {
ev.stopPropagation()
parseInt($(ev.target).data('thingy'), 10) // 57
})
$('.thing-2').click(function (ev) {
ev.stopPropagation()
parseInt($(ev.target).data('thingy'), 10) // 65
})
</script>
当你在click上调用一个函数时,没有事件会作为参数传递,如果你能做到这一点,那不是一个Jquery对象,也不会有stopPropagation
属性。所以你需要为这两个div定义jQuery点击事件处理程序,让我们给他们id div1
和div2
。
<div id="div1" style='background-color:blue;width:500px;height:500px;'>
<div id="div2" style='background-color:red;width:100px;height:100px;'></div>
</div>
在Javascript中,
function thing2(ev) {
// Do something with a
console.log(ev);
alert('hi2');
ev.stopPropagation();
}
function thing1(ev) {
// Do something with a
alert('hi1');
}
$('#div1').click(thing1);
$('#div2').click(thing2);
相关文章:
- jquery设置为使用参数运行
- 嵌入参数中的Javascript函数会自动运行
- 在页面加载完成之前,使用URL参数运行JavaScript
- 使用JavaScript中的参数运行.jar文件
- 如何在函数参数上运行jQueryif语句
- 如何使用参数按顺序运行三个任务
- PHP-如何让别人可以'不要更改url中的参数,也不要在刷新页面时再次运行脚本
- 如何使用 Muse 参数进行布尔比较以运行 JS 函数
- 函数不't在添加括号的情况下调用它时运行(即使它不需要参数)
- 当我尝试在 couchbase nodejs 服务器上运行简单的测试时,我收到“不正确的参数”错误
- 避免传递大量参数以在 JavaScript 中运行的最佳实践
- 在 Ember 视图参数更改上运行代码
- 拉斐尔未运行回调参数
- 块函数在 JavaScript 中作为参数传递时运行
- 使用可选参数器运行
- ng-重复运行次数与整数参数一样多在某些情况下不起作用
- 如何在 jQuery 函数中传递运行时参数
- 将参数传递给包含多个命令的 npm 运行脚本
- Express v4:如何在参数中间件之前运行特定于路由的中间件
- 传入函数数组作为参数,对于函数中的每个函数运行函数