问题
I can't seem to get this:
top.document.getElementById("clickThis").setAttribute("onclick", "tinyMCE.execCommand('mceInsertContent',false,'<div style=\"width: 600px; margin: 0 auto .5em;\" class=\"wp-caption alignnone\"><a href=\"<?php echo $full_image_path; ?>\" rel=\"lightbox\" title=\"View in lightbox\"><img class=\"alignnone\" src=\"<?php echo $full_width; ?>\" alt=\"<?php echo $value; ?>\" /></a><p class=\"wp-caption-text\"><?php echo $get_image->caption; ?></p></div>');");
To work in IE7, I have tried all of the workarounds I could find online and wondering if anyone could help?
回答1:
Don't do that.
Instead, add an event handler by calling attachEvent
/ addEventListener
.
回答2:
I know I'm a bit late, but this was bugging the hell out of me too, and I finally got it.
To get IE to execute dynamically built code during the onclick event, do this:
- Write the code for all other browsers: element.setAttribute( "onclick", object.varName + "method( " + var + " )" );
- Use a custom attribute to hold your dynamic statement: element.setAttribute( "exec", object.varName + "method( " + var + " )" );
- Create an anonymous function to execute the statement stored in our custom attribute when the element is clicked: element.onclick = function(){ eval( this.exec ); };
This approach is working for me in IE9 running in IE7 browser mode, as well as the current versions of Chrome and Firefox.
A couple of things to note:
First, in my case, I needed to execute an objects method. To do that, I need to know the var name for the object, which I set as a property when initiating the class. So the object.varName property is one I created and set in my runtime code.
Second, "exec" is not a standard attribute, which is why it works to hold the string I want to execute. But you can call it what ever you want as long as you use a non-standard attribute.
Third, here's why this works: IE, or at least IE7, will only let you set the onclick event to contain an anonymous function. If you assign an object's method or a variable containing a function, the function is executed when the onclick attribute is set instead of when the element is actually clicked. In my case, I couldn't build an anonymous function because the variables change at runtime. So instead, I dynamically build a statement that is then stored in an attribute of the element. The onclick event then executes whatever statement is stored in that attribute.
Cheers.
回答3:
worked like a dream when I did this:
if(navigator.userAgent.indexOf("MSIE 7.0") != -1){
document.getElementById("pb").onclick = function(){ eval( this.onClick ); };
}
that way only ie7 looks at it.
来源:https://stackoverflow.com/questions/6347236/onclick-setattribute-workaround-for-ie7