当前位置: 动力学知识库 > 问答 > 编程问答 >

jquery - JavaScript event listener for non-input elements

问题描述:

Possible Duplicate:

Is there a jQuery DOM change listener?

How do can watch DOM Object properties?

Is there a way to bind events to non-input-type elements? For example, binding an event to an anchor element that fires when the href attribute is changed.

网友答案:

You can bind handlers to all kinds of events on non-input elements (click, mousemove, etc.). But there is no (consistent cross-browser) event raised when an attribute changes (such as your example of an href attribute on a link). Some attributes (like src) will cause an event (like load) as a secondary thing, as bfavarello pointed out.

(There's a now-dead proposal for "mutation" events on elements, including attribute changes [mutations], but it was never broadly supported. There's a newer proposal, but it is also not [yet] broadly supported.)

You can, of course, use polling: Save the old value, and check back periodically (via setTimeout or setInterval) to see if it has changed. Unless you're checking a lot of elements and need to check them near-constantly, this needn't be a performance problem.

网友答案:

DOM Mutation Observers can do this, but they're very new and not well supported at the time of writing.

Are you writing an extension or similar (ie, you don't control that code that's modifying the DOM)? That's one of the more common use cases for these events - where you don't control the code that's changing the DOM. I've used this before with the Mutation Summary which has worked well in Chrome.

If you do control the code that's modifying the DOM - ie you're modifying the attribute yourself on your own web site - you might wish to simply fire off a custom event of your own when you modify the attribute.

网友答案:

You could add a DomSubtreeModified listener to an ancestor, or you could use watch on the src property of the DOM object if it is supported in the browser you are using.

myImage.watch("src",function(id, oldval, newval){
    document.write("src changed!");
    return newval;    
});
分享给朋友:
您可能感兴趣的文章:
随机阅读: