Ter*_*man 53 html javascript dom
我正在考虑动态设置在我的应用程序中动态创建的HTML输入元素的ID属性.
我的实现在Firefox中使用setAttribute方法可以正常工作.有关IE中工作实现的任何想法或解决方案将不胜感激.
var hiddenInput = document.createElement("input");
hiddenInput.setAttribute("id", "uniqueIdentifier");
hiddenInput.setAttribute("type", "hidden");
hiddenInput.setAttribute("value", ID);
hiddenInput.setAttribute("class", "ListItem");
Run Code Online (Sandbox Code Playgroud)
我修改了一些示例代码,这些代码来自与此问题相关的博客,提示以下workround.Firefox位运行良好,但IE位不行
var hiddenInput = null;
try {
hiddenInput = document.createElement('<input name=\''+"hiddenInputName"+'\' />');
hiddenInput.id = "uniqueIdentifier";
//alert(document.getElementById("uniqueIdentifier"));
hiddenInput.type = "hidden";
} catch (e) { }
if (!hiddenInput || !hiddenInput.name) { // Not in IE, then
var hiddenInput = document.createElement("input");
hiddenInput.setAttribute("id", "uniqueIdentifier");
hiddenInput.setAttribute("type", "hidden");
}
Run Code Online (Sandbox Code Playgroud)
干杯.
gor*_*gor 74
此代码适用于IE7和Chrome:
var hiddenInput = document.createElement("input");
hiddenInput.setAttribute("id", "uniqueIdentifier");
hiddenInput.setAttribute("type", "hidden");
hiddenInput.setAttribute("value", 'ID');
hiddenInput.setAttribute("class", "ListItem");
$('body').append(hiddenInput);
Run Code Online (Sandbox Code Playgroud)
也许在其他地方有问题?
Tim*_*own 65
忘了setAttribute():它已经严重破坏了,并不总能做到你在旧IE中所期望的(IE <= 8和更高版本的兼容模式).请改用元素的属性.这通常是一个好主意,不仅仅是针对这种特殊情况.用以下内容替换您的代码,这将适用于所有主流浏览器:
var hiddenInput = document.createElement("input");
hiddenInput.id = "uniqueIdentifier";
hiddenInput.type = "hidden";
hiddenInput.value = ID;
hiddenInput.className = "ListItem";
Run Code Online (Sandbox Code Playgroud)
更新
问题中第二个代码块中令人讨厌的黑客是不必要的,上面的代码在所有主流浏览器中运行良好,包括IE 6.请参阅http://www.jsfiddle.net/timdown/aEvUT/.你进入null你的原因alert()是,当它被调用时,新的输入还没有在文档中,因此document.getElementById()调用无法找到它.
使用jquery attr方法.它适用于所有浏览器.
var hiddenInput = document.createElement("input");
$(hiddenInput).attr({
'id':'uniqueIdentifier',
'type': 'hidden',
'value': ID,
'class': 'ListItem'
});
Run Code Online (Sandbox Code Playgroud)
或者您可以使用以下代码:
var e = $('<input id = "uniqueIdentifier" type="hidden" value="' + ID + '" class="ListItem" />');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
251789 次 |
| 最近记录: |