jQuery method fails on IE
I have t开发者_开发技巧his method:
function replaceRightClickIcefacesMethod() {
var oldName = jQuery(".singlePaneOfGlassBlock").attr("oncontextmenu");
oldName = oldName.replace('Ice.Menu.contextMenuPopup', 'contextMenuPopupUpdated');
alert(oldName);
jQuery(".singlePaneOfGlassBlock").attr("oncontextmenu", oldName);
}
which works nice on Chrome or FF. BUT on IE I receive this complaining:
Object does not support this property or method
and it's pointing me to the 3rd line..
Do you see any work-around?
Ps: I'm using latest version of jQuery (1.6)
UPDATE:
I've also tried with:
var oldName = jQuery(".singlePaneOfGlassBlock")[0].getAttribute('oncontextmenu');
but still the same problem for IE
This is a problem with Internet Explorer versions before IE 8. attr()
maps to getAttribute
for event handlers, but older IEs had a bug which caused getAttribute
to just return the DOM property value instead of the attribute string.
I can't think of a way around it, save for parsing the outerHTML
string in IE, which you really don't want to do :-)
The best approach, for all browsers, is to bind
to the event using jQuery in the first place:
$(".singlePaneOfGlassBlock").bind("contextmenu", contextMenuPopupUpdated);
And then swap to a different function (unbind
, then bind
again) when you need to:
function replaceRightClickIcefacesMethod() {
$(".singlePaneOfGlassBlock").unbind().bind("contextmenu", function () {
Ice.Menu.contextMenuPopup();
});
}
As you figured out, you can use getAttributeNode()
to get the string value of the node. In order to set the attribute, you have to create a function from the string before assigning it. A simple approach to this might be:
function replaceRightClickIcefacesMethod() {
var elem = jQuery(".singlePaneOfGlassBlock"),
oldName = elem.attr("oncontextmenu"),
fn = String;
if (typeof oldName == "function")
oldName = elem[0].getAttributeNode("oncontextmenu").value,
fn = Function;
oldName = oldName.replace('Ice.Menu.contextMenuPopup', 'contextMenuPopupUpdated');
alert(oldName);
elem[0].setAttribute("oncontextmenu", fn(oldName));
}
This passes the string to String
if the original type is a string, which will have no real effect, but if the original type is a function, the resulting string is passed to Function
before being set as the new value for the attribute.
I was able to get it as string instead of function (as it was in IE) like this:
var oldName = jQuery(".singlePaneOfGlassBlock")[0].getAttributeNode("oncontextmenu").value;
精彩评论