jQuery onchange 检测
我想执行 html 元素的“onchange”属性中的 javascript。所以..
<input id="el" type="text" onchange="alert('test');" value="" />
使用该示例,我想通过 jQuery 执行 alert('test');
部分,问题是 .change()
事件处理程序不是不起作用,因为我想在另一个元素更改其值后执行它。所以..
$('#el').val('test');
这是我想执行onchange的时候。之后 .val
val 被调用。有什么想法吗?
I want to execute javascript that's in the "onchange" attribute of an html element. So..
<input id="el" type="text" onchange="alert('test');" value="" />
Using that example I'd like to execute the alert('test');
portion via jQuery, the problem is the .change()
event handler isn't working, because I want to execute it after another element changes it's value. So..
$('#el').val('test');
This is when I'd like to execute the onchange. After that .val
val has been called. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
.val()
不会触发change
事件。您需要自己手动执行此操作。例如:您可以将其封装在一个小的 jQuery 插件中,如下所示:
.val()
does not triggerchange
events. You need to do so yourself, manually. For example:You can encapsulate this in a small jQuery plugin like so:
我认为当字段值发生变化时 onchange 事件总是触发是有道理的。因此,我会更改 JQuery 本身中的 val 函数,而不是创建自定义函数。这样,您就不必担心使用哪个函数来设置对象的值,并且如果您已经使用过 JQuery,则不必更改所有
val
调用编写您的应用程序。这是代码:I think it makes sense that the onchange event ALWAYS fires when the value of the field changes. Thus, I would change the
val
function in JQuery itself rather than make a custom function. That way, you don't have to worry about which function you use to set the value of an object, and don't have to go change all of yourval
calls if you've already used JQuery to code your app. Here's the code:不久前我也遇到了同样的问题,但找不到任何好的解决方案。似乎最好的解决方案是对输入进行“拉动”,或者从实际更改输入内容的代码中触发 onchange 函数(如 Domenic 所示)。
I had the same problem a while ago, but couldn't find any good solutions to it. It seems the best solution is to do a "pull" on the input, or to fire your onchange function (like Domenic shows) from the code that actually changes the content of the input.
如果你先
input.focus();
然后$.val('abcd');
将触发更改事件。取自 jquery 站点。
if you first
input.focus();
then$.val('abcd');
a change event will be fired.taken from jquery site.
我会重新设计并开始使用 knockout.js 插件,该插件使用数据绑定,让您可以轻松使用所有绑定。
示例代码如下:
};
ko.applyBindings(new ViewModel("行星", "地球"));
I Would redesign and start using knockout.js plugin which is using data-bind where let u use all the binding pretty easy.
sample code below:
};
ko.applyBindings(new ViewModel("Planet", "Earth"));