javascript - Intercept submit event
问题描述
I want to build a simple Google extensions that would stop users to submit a tweet if it contains a blacklisted word. This requires that I can intercept the click on "Tweet" that would submit it.
After inspecting the Twitter page, I currently use the following code in the content script:
$('button.tweet-action').click(function(e) {
console.log(e);
e.preventDefault();
e.stopPropagation();
return false;
});
When I click "Tweet" then I get the console output but the tweet is still submitted. Interestingly, when I use only $('button')
then it works with many buttons. For example, I cannot delete a tweet anymore. So it kind of works just not for submitting new tweets, and I cannot tell why that's the case. Here's the snippet from Twitter HTML page:
How can I intercept and stop the submission of tweets.
Update: I've tried intercepting the form submit as suggest below. Since the form doesn't have an id, I used a class selector:
$('.tweet-form').submit(function(e) {
console.log(e);
e.preventDefault();
e.stopPropagation();
return false;
});
But it's not working. For a trivial test I tried $('.tweet-form').css(...)
which successfully changed some style changes. However intercepting the submit doesn't work; I don't even see the console output. Maybe that's because there's no type="submit"
anywhere between the form tags.
解决方案
拦截按钮单击事件可stopImmediatePropagation()
改为使用stopPropagation()
。问题是这个按钮已经附加了一个点击处理程序,并且stopPropagation()
只影响父事件处理程序。添加新的单击事件处理程序不会覆盖现有的事件处理程序。stopImmediatePropagation()
防止调用同一事件的其他侦听器。
因此,工作解决方案如下所示:
$('button.tweet-action').click(function(e) {
console.log(e);
e.preventDefault();
e.stopImmediatePropagation();
return false;
});
推荐阅读
- mongodb - 使用 Morphia 或 Mongo java 驱动程序检查查询是否匹配文档
- javascript - 从对象数组中创建对象的特定字段数组
- c - 文件指针是否导致代码中的分段错误
- java - AssertJ:递归否定 isEqualToComparingFieldByField
- mysql - 根据最早日期更新所有记录
- c# - 以编程方式创建没有源或目标的数据流任务
- javascript - WMS 图层未在所有缩放级别上正确渲染
- ruby-on-rails - root_url 返回空字符串
- laravel - Laravel 关系有很多不起作用
- amazon-web-services - 在ec2(中国的ec2)部署美国AWS beanstalk环境后,在aws china beanstalk环境下无法获取平台信息