JavaScript/jQuery - 如何区分触发和用户点击?

7

这个问题看起来很像在Jquery中,我如何区分编程和用户点击?

但是我无法理解它,我的代码

<div class="sample_class" onclick="sample_fn(arg1,arg2,arg3,arg4, e);" ></div>
<div class="trigger_class" onclick="trigger_fn()></div>


function sample_fn(arg1,arg2,arg3,arg4, e){
    console.log(e) ;
    console.log(e.isTrigger);
    console.log(e.hasOwnProperty('originalEvent'));
}


function trigger_fn(){
    $(".sample_class").trigger("click")
}

当点击 div.sample_class 时,我在控制台中得到了以下内容: Object undefined false

当点击 div.tigger_class 时,我在控制台中得到了相同的内容: Object undefined false

我无法区分这两个点击事件。 提前致谢。


1
那你为什么要模拟点击呢?编写一个不共享相同代码的新函数。您还可以阅读event namespacingcustom events,看看它们是否有助于您的情况。 - Blazemonger
1
在你的HTML中,你有onclick="tigger_fn()",而在Javascript中你有function trigget_fn()——拼写错误不会帮助任何东西工作。如果它们不在你的实际代码中,它们也不应该出现在你的问题中。 - Anthony Grist
错别字已经被更正了......实际上它不在代码中。 - druveen
使用 e.isTrusted 来识别用户操作触发的事件。 - mohit bansal
1个回答

9
更新:自jQuery 1.7+起,事件对象(下面代码中的e)将包含一个名为e.isTrigger的属性,如果事件被触发,则该属性值为true,如果未被触发,则为未定义;这是未记录在案的,请在使用之前检查此示例(demo)。如果使用较旧版本的jQuery,请使用以下代码。


向函数传递标志可能更容易。这是一个演示

HTML

<button>Trigger a click below</button>

<div id="test">Click Me</div>​

脚本
​$('#test').click(function(e, triggered){
    var msg = (triggered) ? ', triggered' : '';
    console.log('clicked' + msg);
});​​

$('button').click(function(){
    // pass a true flag to the click function to indicate
    // it's been triggered
    $('#test').trigger('click', true);
});

更新:data-attributes可以包含有效的JSON,这些JSON将自动转换为对象(演示):

<div class="test" data-args='{ "quantity": 1, "type": "pizza", "extra1": "peperoni", "extra2": "cheese", "extra3": "cheesy bread" }'>Click Me</div>

请注意,data-arg 使用单引号来包含 JSON,但 JSON 内部必须使用双引号来包含每个键和值(除非是数字)。
然后使用 data 方法提取信息:
var args = $(this).data('args');

或者,您可以为每个参数创建一个单独的数据属性(演示):

<div class="test" data-quantity="1" data-type="pizza" data-extra1="peperoni" data-extra2="cheese" data-extra3="cheesy bread">Click Me</div>

然后按照以下方式收集元素中的所有数据:
var args = $(this).data();

不需要使用 onclick,你可以将特定的参数添加到数据属性中,并以这种方式获取它们。 - Mottie
返回已翻译的文本: 或[执行此操作](http://jsfiddle.net/Mottie/hQAWv/1/):`function trigger_fn(e){test_fn(e,true);}` - Mottie
但是我有很多额外的参数需要传递。 - druveen
感谢data-attributes,这对我来说是新的。但是我通过设置全局变量true/false来管理。 - druveen
1
没问题,我只是在向您展示如何使用数据属性编写不侵入式JavaScript - Mottie
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接