如何以编程方式强制输入onchange事件?

时间:2022-09-26 20:49:28

How do I programmatically force an onchange event on an input?

如何以编程方式强制输入onchange事件?

I've tried something like this:

我尝试过这样的事情:

var code = ele.getAttribute('onchange');
eval(code);

But my end goal is to fire any listener functions, and that doesn't seem to work. Neither does just updating the 'value' attribute.

但我的最终目标是解雇任何监听器功能,这似乎不起作用。也不只是更新'value'属性。

7 个解决方案

#1


45  

Create an Event object and pass it to the dispatchEvent method of the element:

创建一个Event对象并将其传递给元素的dispatchEvent方法:

var element = document.getElementById('just_an_example');
var event = new Event('change');
element.dispatchEvent(event);

This will trigger event listeners regardless of whether they were registered by calling the addEventListener method or by setting the onchange property of the element.

这将触发事件侦听器,无论它们是通过调用addEventListener方法还是通过设置元素的onchange属性进行注册。


If you want the event to bubble, pass a second argument to the Event constructor:

如果您希望事件冒泡,请将第二个参数传递给Event构造函数:

var event = new Event('change', { bubbles: true });

Information about browser compability:

有关浏览器兼容性的信息:

#2


85  

In jQuery I mostly use:

在jQuery我主要使用:

$("#element").trigger("change");

#3


59  

ugh don't use eval for anything. Well, there are certain things, but they're extremely rare. Rather, you would do this:

呃不要用eval做任何事情。嗯,有一些事情,但它们非常罕见。相反,你会这样做:

document.getElementById("test").onchange()

Look here for more options: http://jehiah.cz/archive/firing-javascript-events-properly

在这里查看更多选项:http://jehiah.cz/archive/firing-javascript-events-properly

#4


21  

For some reason ele.onchange() is throwing a "method not found" expception for me in IE on my page, so I ended up using this function from the link Kolten provided and calling fireEvent(ele, 'change'), which worked:

出于某种原因,ele.onchange()在我的页面上为我在IE中抛出了一个“找不到方法”的表示,所以我最终使用了Kolten提供的链接并调用fireEvent(ele,'change')这个函数, :

function fireEvent(element,event){
    if (document.createEventObject){
        // dispatch for IE
        var evt = document.createEventObject();
        return element.fireEvent('on'+event,evt)
    }
    else{
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
}

I did however, create a test page that confirmed calling should onchange() work:

但是,我创建了一个测试页面,确认调用onchange()工作:

<input id="test1" name="test1" value="Hello" onchange="alert(this.value);"/>
<input type="button" onclick="document.getElementById('test1').onchange();" value="Say Hello"/>

Edit: The reason ele.onchange() didn't work was because I hadn't actually declared anything for the onchange event. But the fireEvent still works.

编辑:ele.onchange()不起作用的原因是因为我实际上没有为onchange事件声明任何内容。但fireEvent仍然有效。

#5


2  

Taken from the bottom of QUnit

取自QUnit的底部

function triggerEvent( elem, type, event ) {
    if ( $.browser.mozilla || $.browser.opera ) {
        event = document.createEvent("MouseEvents");
        event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
            0, 0, 0, 0, 0, false, false, false, false, 0, null);
        elem.dispatchEvent( event );
    } else if ( $.browser.msie ) {
        elem.fireEvent("on"+type);
    }
}

You can, of course, replace the $.browser stuff to your own browser detection methods to make it jQuery independent.

当然,您可以将$ .browser内容替换为您自己的浏览器检测方法,以使其独立于jQuery。

To use this function:

要使用此功能:

var event;
triggerEvent(ele, "change", event);

This will basically fire the real DOM event as if something had actually changed.

这基本上会触发真正的DOM事件,就好像某些事实已经发生了变化。

#6


-3  

if you're using jQuery you would have:

如果你使用的是jQuery,你会得到:

$('#elementId').change(function() { alert('Do Stuff'); });

or MS AJAX:

或MS AJAX:

$addHandler($get('elementId'), 'change', function(){ alert('Do Stuff'); });

Or in the raw HTML of the element:

或者在元素的原始HTML中:

<input type="text" onchange="alert('Do Stuff');" id="myElement" />

After re-reading the question I think I miss-read what was to be done. I've never found a way to update a DOM element in a manner which will force a change event, what you're best doing is having a separate event handler method, like this:

在重新阅读这个问题后,我想我错过了 - 读了要做的事情。我从未找到过以强制更改事件的方式更新DOM元素的方法,您最好的做法是使用单独的事件处理程序方法,如下所示:

$addHandler($get('elementId'), 'change', elementChanged);
function elementChanged(){
  alert('Do Stuff!');
}
function editElement(){
  var el = $get('elementId');
  el.value = 'something new';
  elementChanged();
}

Since you're already writing a JavaScript method which will do the changing it's only 1 additional line to call.

由于您已经编写了一个JavaScript方法,它将更改它只需要另外一行来调用。

Or, if you are using the Microsoft AJAX framework you can access all the event handlers via:

或者,如果您使用的是Microsoft AJAX框架,则可以通过以下方式访问所有事件处理程序:

$get('elementId')._events

It'd allow you to do some reflection-style workings to find the right event handler(s) to fire.

它允许你做一些反射式的工作来找到要触发的正确的事件处理程序。

#7


-4  

Using JQuery you can do the following:

使用JQuery,您可以执行以下操作:

// for the element which uses ID
$("#id").trigger("change");

// for the element which uses class name
$(".class_name").trigger("change");

#1


45  

Create an Event object and pass it to the dispatchEvent method of the element:

创建一个Event对象并将其传递给元素的dispatchEvent方法:

var element = document.getElementById('just_an_example');
var event = new Event('change');
element.dispatchEvent(event);

This will trigger event listeners regardless of whether they were registered by calling the addEventListener method or by setting the onchange property of the element.

这将触发事件侦听器,无论它们是通过调用addEventListener方法还是通过设置元素的onchange属性进行注册。


If you want the event to bubble, pass a second argument to the Event constructor:

如果您希望事件冒泡,请将第二个参数传递给Event构造函数:

var event = new Event('change', { bubbles: true });

Information about browser compability:

有关浏览器兼容性的信息:

#2


85  

In jQuery I mostly use:

在jQuery我主要使用:

$("#element").trigger("change");

#3


59  

ugh don't use eval for anything. Well, there are certain things, but they're extremely rare. Rather, you would do this:

呃不要用eval做任何事情。嗯,有一些事情,但它们非常罕见。相反,你会这样做:

document.getElementById("test").onchange()

Look here for more options: http://jehiah.cz/archive/firing-javascript-events-properly

在这里查看更多选项:http://jehiah.cz/archive/firing-javascript-events-properly

#4


21  

For some reason ele.onchange() is throwing a "method not found" expception for me in IE on my page, so I ended up using this function from the link Kolten provided and calling fireEvent(ele, 'change'), which worked:

出于某种原因,ele.onchange()在我的页面上为我在IE中抛出了一个“找不到方法”的表示,所以我最终使用了Kolten提供的链接并调用fireEvent(ele,'change')这个函数, :

function fireEvent(element,event){
    if (document.createEventObject){
        // dispatch for IE
        var evt = document.createEventObject();
        return element.fireEvent('on'+event,evt)
    }
    else{
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
}

I did however, create a test page that confirmed calling should onchange() work:

但是,我创建了一个测试页面,确认调用onchange()工作:

<input id="test1" name="test1" value="Hello" onchange="alert(this.value);"/>
<input type="button" onclick="document.getElementById('test1').onchange();" value="Say Hello"/>

Edit: The reason ele.onchange() didn't work was because I hadn't actually declared anything for the onchange event. But the fireEvent still works.

编辑:ele.onchange()不起作用的原因是因为我实际上没有为onchange事件声明任何内容。但fireEvent仍然有效。

#5


2  

Taken from the bottom of QUnit

取自QUnit的底部

function triggerEvent( elem, type, event ) {
    if ( $.browser.mozilla || $.browser.opera ) {
        event = document.createEvent("MouseEvents");
        event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
            0, 0, 0, 0, 0, false, false, false, false, 0, null);
        elem.dispatchEvent( event );
    } else if ( $.browser.msie ) {
        elem.fireEvent("on"+type);
    }
}

You can, of course, replace the $.browser stuff to your own browser detection methods to make it jQuery independent.

当然,您可以将$ .browser内容替换为您自己的浏览器检测方法,以使其独立于jQuery。

To use this function:

要使用此功能:

var event;
triggerEvent(ele, "change", event);

This will basically fire the real DOM event as if something had actually changed.

这基本上会触发真正的DOM事件,就好像某些事实已经发生了变化。

#6


-3  

if you're using jQuery you would have:

如果你使用的是jQuery,你会得到:

$('#elementId').change(function() { alert('Do Stuff'); });

or MS AJAX:

或MS AJAX:

$addHandler($get('elementId'), 'change', function(){ alert('Do Stuff'); });

Or in the raw HTML of the element:

或者在元素的原始HTML中:

<input type="text" onchange="alert('Do Stuff');" id="myElement" />

After re-reading the question I think I miss-read what was to be done. I've never found a way to update a DOM element in a manner which will force a change event, what you're best doing is having a separate event handler method, like this:

在重新阅读这个问题后,我想我错过了 - 读了要做的事情。我从未找到过以强制更改事件的方式更新DOM元素的方法,您最好的做法是使用单独的事件处理程序方法,如下所示:

$addHandler($get('elementId'), 'change', elementChanged);
function elementChanged(){
  alert('Do Stuff!');
}
function editElement(){
  var el = $get('elementId');
  el.value = 'something new';
  elementChanged();
}

Since you're already writing a JavaScript method which will do the changing it's only 1 additional line to call.

由于您已经编写了一个JavaScript方法,它将更改它只需要另外一行来调用。

Or, if you are using the Microsoft AJAX framework you can access all the event handlers via:

或者,如果您使用的是Microsoft AJAX框架,则可以通过以下方式访问所有事件处理程序:

$get('elementId')._events

It'd allow you to do some reflection-style workings to find the right event handler(s) to fire.

它允许你做一些反射式的工作来找到要触发的正确的事件处理程序。

#7


-4  

Using JQuery you can do the following:

使用JQuery,您可以执行以下操作:

// for the element which uses ID
$("#id").trigger("change");

// for the element which uses class name
$(".class_name").trigger("change");