【发布时间】:2015-11-02 17:42:28
【问题描述】:
尝试创建 Chrome 扩展,我使用 jQuery 使用以下语句更改某些 input 和 textarea 值:
$(this).val(newValue).trigger('change');
trigger 部分的目标是通知当前页面上使用的任何 2 路数据绑定模块 input 的值已更改。
它不起作用。
我尝试使用Knockout 和Rivets,但都不知道input 的值已使用上述jQuery 行更改。
使用接受的答案here,我尝试了:
$(this).val(newValue).change();
这也不起作用。
有趣的是,如果我降级到纯 DOM 接口(即没有 jQuery),那么它可以正常工作,并且 2 路绑定会正确通知值更改。使用以下代码:
element.value = newValue;
element.dispatchEvent(new Event('change'));
上述工作和我尝试的所有 2 路绑定模块都知道值的变化。
如何使用 jQuery 实现相同的效果?请注意,我的代码位于 Chrome 扩展程序的内容脚本中。
【问题讨论】:
-
data binding modules used on the current page- 在这种情况下,您必须将脚本注入页面:Building a Chrome Extension - Inject code in a page using a Content script -
@wOxxOm 这是有道理的。我必须将 jQuery 注入页面,所以它不能单独工作。
-
可以在注入的代码中复用网页的jQuery。否则别忘了使用
jQuery.noConflict()。
标签: jquery knockout.js google-chrome-extension