使用跨浏览器支持的jQuery更改类型

问题

以下脚本完全符合我的要求,在除IE8之外的所有测试的浏览器中,它删除按钮而不用任何替换它。

背景

我一直在研究一种方法,用jQuery替换提交类型输入和图像类型输入。

首先,我有以下内容适用于FF和webkit:

marker = jQuery('').insertBefore('input#SearchButton'); jQuery('input#SearchButton').detach().attr('type', 'image').attr('src',theme_folder+'/style/images/search_button.png').insertAfter(marker); marker.remove(); 

但是,如果IE(它删除按钮,但不替换为图像),所有6个版本都会失败,所以我为IE浏览器开发了以下脚本:

  marker = jQuery('').insertBefore('input#SearchButton'); new_search = jQuery('') jQuery(new_search).insertAfter('input#SearchButton'); jQuery('input#SearchButton').remove(); marker.remove(); 

我正在使用HTML Conditionals来过滤到适当脚本的流量,所以整个事情看起来像这样:

    marker = jQuery('').insertBefore('input#SearchButton'); jQuery('input#SearchButton').detach().attr('type', 'image').attr('src',theme_folder+'/style/images/search_button.png').insertAfter(marker); marker.remove();   

在IE上, input元素的type属性是write-once 。 第一次设置后,您无法更改它。 (在attr文档中有关于此的警告。)

与IE兼容的唯一真正选择是用一个具有相同id的新元素替换元素。 显然这对事件处理程序有影响(任何你附加到旧元素的东西都不会附加到新元素上),所以你可能想要使用delegate (或全局版本, live )而不是直接将处理程序附加到有问题的元素。

更新 :啊,我看到你写了一些代码来做到这一点。 该代码的问题在于您临时创建了一个无效文档(它有两个具有相同id不同元素),然后通过该重复id查找该元素。 如果您只是提前抓住元素,那就好了:

 // Get the old search button old_search = jQuery('input#SearchButton'); // Create the new search button new_search = jQuery('') // Insert the new one after the old (temporarily creates an invalid document) jQuery(new_search).insertAfter(old_search); // Now remove the old one old_search.remove(); 

(你不需要这个标记,所以我从上面删除它。)

但您可能希望使用replaceWith代替:

 jQuery('input#SearchButton').replaceWith( '' ); 

这是一个简化的replaceWith示例(也演示delegate ):

HTML:

 

This button is in the container, and so clicks on it will convert it back and forth between input type='button' and input type='image'.

This button is not in the container, and so clicks on it aren't processed.

JavaScript的:

 $('#container').delegate('input', 'click', function() { if (this.type === "button") { $(this).replaceWith( "" ); } else { $(this).replaceWith( "" ); } }); 

实时复制

那里的按钮没有id ,但如果它有以下情况则完全没问题:

HTML:

 

JavaScript的:

 $('#container').delegate('#theButton', 'click', function() { if (this.type === "button") { $(this).replaceWith( '' ); } else { $(this).replaceWith( '' ); } }); 

实时复制


偏离主题 :因为你必须更换元素以支持IE,我建议只使用一个代码副本并在所有浏览器上使用它。 即使在允许您更改元素的浏览器上,替换元素也不是那么昂贵。

您无法在Internet Explorer中动态更改输入元素的类型。 您必须删除旧输入并添加新输入