开发者

IE 7 does not like jquery('<button/>').attr('type','button')

开发者 https://www.devze.com 2022-12-30 04:32 出处:网络
I am trying to create a button开发者_C百科 using jquery. I use the following code jquery(\'<button/>\', {type:\'button\'}).text(name)

I am trying to create a button开发者_C百科 using jquery. I use the following code

jquery('<button/>', {type:'button'}).text(name)

However this works in Safari , FF IE8 but not IE7

i tried to use the attr function :

jquery('<button/>').attr('type','button').text(name)

this does not work either.

any ideas what would work? I suppose if I don't assign a type it would default to button but i rather do that

thanks for your help


Try this:

var button = $('<button type="button"/>');

Now, as it happens, the default type for buttons is "button" anyway in IE (7 at least, not sure about standards-mode 8). However the above should work. I just ran into this the other day. IE lets you provide the type right there in the element syntax when creating elements, and it seems that jQuery is pretty much passing its argument straight through to the low-level DOM API here.

Oh, and it works fine in FF and Chrome too.


edit — well what a difference a year makes, eh? I cannot get that mechanism to work for me at all now with jQuery 1.4.4 or jQuery 1.5.x. The good news is that jQuery 1.6 appears to work the way the OP wanted: via setting "type" in a more normal jQuery-like way.

What does seem to work, however, is to directly call ".setAttribute()" on the element. Thus:

var b = $('<button/>');
b[0].setAttribute('type', 'button');

does not throw an exception, and it does set the "type" attribute properly. (That's itself a little bizarre, as Microsoft clearly documents "type" as being read-only.) The change in 1.6 seems to be along the same lines. Formerly, the library did check "type" and would explicitly disallow its being set on elements already in the DOM, but would proceed to try and set it as a simple attribute for an element not in the DOM. Now, the 1.6 code calls ".setAttribute()" to set "type", which (for reasons unknown to me) works fine.


Have you tried:

var $btn = $("<button>Button Text</button>");

Then you can append this anywhere in your document. Generally, you can create just about any DOM element using a string literal in this manner.


I think you want to use this $(':submit')

It finds anything that acts as a submit button. See: http://api.jquery.com/submit-selector/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号