我想执行html元素的“onchange”属性中的javascript。所以..
<input id="el" type="text" onchange="alert('test');" value="" />
使用该示例我想通过jQuery执行al ert('test');
部分,问题是.change()
事件处理程序无法正常工作,因为我想在另一个元素更改它之后执行它值。所以..
$('#el').val('test');
这是我想执行onchange的时候。之后调用.val
val。有什么想法吗?
答案 0 :(得分:6)
.val()
不会触发change
个事件。你需要自己手动完成。例如:
$('#el').val('test').change();
你可以将它封装在一个小的jQuery插件中,如下所示:
(function ($) {
$.fn.changeVal = function (text) {
this.val(text).change();
};
}(jQuery));
$('#el').changeVal('test');
答案 1 :(得分:2)
我认为当字段的值发生变化时,onchange事件总是会触发。因此,我会更改JQuery本身的val
函数,而不是自定义函数。这样,您不必担心用于设置对象值的函数,如果您已使用JQuery编写代码,则无需更改所有val
调用应用程序。这是代码:
//Store the old val function
$.fn.custom_oldVal = $.fn.val;
//Update the val function to fire the change event where appropriate:
$.fn.val = function(value) {
if(value == null || value == undefined){
return this.custom_oldVal();
} else {
//Only call onchange if the value has changed
if(value == this.custom_oldVal()){
return this;//Return this object for chain processing
} else {
return this.custom_oldVal(value).change();
}
}
}
答案 2 :(得分:0)
前一段时间我遇到了同样的问题,但找不到任何好的解决方案。似乎最好的解决方案是对输入进行“拉动”,或者从实际更改输入内容的代码中激活onchange函数(如Domenic节目)。
答案 3 :(得分:0)
如果你是第一个
input.focus();
然后$.val('abcd');
将触发更改事件
取自jquery网站。
答案 4 :(得分:-1)
我会重新设计并开始使用knockout.js插件,它使用数据绑定,让你使用所有绑定非常简单。
以下示例代码:
var ViewModel = function(first, last) {
this.firstName = ko.observable(first);
this.lastName = ko.observable(last);
this.fullName = ko.computed(function() {
// Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
return this.firstName() + " " + this.lastName();
}, this);
};
ko.applyBindings(new ViewModel(“Planet”,“Earth”));