Javascript 在 IE 中动态设置输入元素的 id 属性:setAttribute 方法的替代方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4851699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:25:26  来源:igfitidea点击:

setting the id attribute of an input element dynamically in IE: alternative for setAttribute method

javascripthtmldom

提问by Terman

I'm looking at dynamically setting the ID attribute of HTML Input elements which are created dynamically in my application.

我正在考虑动态设置在我的应用程序中动态创建的 HTML Input 元素的 ID 属性。

My implementation works fine with the setAttribute method in Firefox. Any ideas or solutions on a working implementation in IE would be appreciated.

我的实现与 Firefox 中的 setAttribute 方法配合良好。任何关于 IE 中工作实现的想法或解决方案将不胜感激。

 var hiddenInput = document.createElement("input");
    hiddenInput.setAttribute("id", "uniqueIdentifier");
    hiddenInput.setAttribute("type", "hidden");                     
    hiddenInput.setAttribute("value", ID);
    hiddenInput.setAttribute("class", "ListItem");

I modified some sample code from blogs relating to this problem that suggest the following workround. Again the Firefox bit works well but the IE bit doens't

我修改了与此问题相关的博客中的一些示例代码,建议以下解决方法。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");                     

            }

Cheers.

干杯。

回答by gor

This codework in IE7 and Chrome:

代码适用于 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);

Maybe problem somewhere else ?

也许其他地方的问题?

回答by Tim Down

Forget setAttribute(): it's badly broken and doesn't always do what you might expect in old IE (IE <= 8 and compatibility modes in later versions). Use the element's properties instead. This is generally a good idea, not just for this particular case. Replace your code with the following, which will work in all major browsers:

忘记setAttribute():它已经严重损坏并且并不总是按照您在旧 IE 中的预期(IE <= 8 和更高版本中的兼容模式)执行。改用元素的属性。这通常是一个好主意,不仅适用于这种特殊情况。将您的代码替换为以下内容,这将适用于所有主要浏览器:

var hiddenInput = document.createElement("input");
hiddenInput.id = "uniqueIdentifier";
hiddenInput.type = "hidden";                     
hiddenInput.value = ID;
hiddenInput.className = "ListItem";

Update

更新

The nasty hack in the second code block in the question is unnecessary, and the code above works fine in all major browsers, including IE 6. See http://www.jsfiddle.net/timdown/aEvUT/. The reason why you get nullin your alert()is that when it is called, the new input is not yet in the document, hence the document.getElementById()call cannot find it.

问题中第二个代码块中令人讨厌的 hack 是不必要的,上面的代码在所有主要浏览器中都可以正常工作,包括 IE 6。请参阅http://www.jsfiddle.net/timdown/aEvUT/。你进入null你的原因alert()是当它被调用时,新的输入还没有在文档中,因此document.getElementById()调用找不到它。

回答by gor

Use jquery attrmethod. It works in all browsers.

使用 jquery attr方法。它适用于所有浏览器。

var hiddenInput = document.createElement("input");
$(hiddenInput).attr({
    'id':'uniqueIdentifier',
    'type': 'hidden',
    'value': ID,
    'class': 'ListItem'
});

Or you could use folowing code:

或者您可以使用以下代码:

var e = $('<input id = "uniqueIdentifier" type="hidden" value="' + ID + '" class="ListItem" />');

回答by jAndy

I wasn't aware of a problem with setAttributein IE ? However you could directly set the expando property on the node itself:

我不知道setAttributeIE有问题?但是,您可以直接在节点本身上设置 expando 属性:

hiddenInput.id = "uniqueIdentifier";

回答by gor

The documentationsays:

文件说:

When you need to set attributes that are also mapped to a JavaScript dot-property (such as href, style, src or event-handlers), favour that mapping instead.

当您需要设置也映射到 JavaScript 点属性(例如 href、样式、src 或事件处理程序)的属性时,请改用该映射。

So, just change id, valueassignment and you should be done.

因此,只需更改id分配,您就应该完成。

回答by Kristofer K?llsbo

I had the same issue! I was unable to change/set the ID attribute of elements. It worked in all other browsers but not IE. It probably isn't relevant to your problem but here is what I ended up doing:

我遇到过同样的问题!我无法更改/设置元素的 ID 属性。它适用于所有其他浏览器,但不适用于 IE。它可能与您的问题无关,但这是我最终做的:

Background

背景

I was building an MVC site with jquery tabs. I wanted to create tabs dynamically and do an AJAX postback to the server saving the tab in the database. I wanted to use a unique identifier, in the form of an int, for the tabs so I wouldn't get in to trouble if a user created two tabs with the same name. I then used the unique ID to identify the tabs like:

我正在使用 jquery 选项卡构建一个 MVC 站点。我想动态创建选项卡并对服务器执行 AJAX 回发,将选项卡保存在数据库中。我想为选项卡使用一个 int 形式的唯一标识符,这样如果用户创建了两个同名的选项卡,我就不会遇到麻烦。然后我使用唯一 ID 来识别标签,如:

<ul>
<li><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close'>Remove List</span></li>
<ul>

When I then implemented the remove functions on the tabs the callback uses the index, witch is 0 based. Then I had no way to sending back the unique ID to the server to trash the DB entry. The callback for the tabremove event gives the jquery event and ui parameters. With one line of code I could get the ID of the span:

当我在选项卡上实现删除功能时,回调使用索引,女巫是基于 0 的。然后我无法将唯一 ID 发送回服务器以删除 DB 条目。tabremove 事件的回调给出了 jquery 事件和 ui 参数。通过一行代码,我可以获得跨度的 ID:

var dbIndex = event.currentTarget.id;

The problem was that the span tag didn't have any ID. So in the create callback I tried to set the ID buy extracting the ID from the a href like this:

问题是 span 标签没有任何 ID。因此,在创建回调中,我尝试设置从 a href 中提取 ID 的 ID 购买,如下所示:

ui.tab.parentNode.id = ui.tab.href.substring(ui.tab.href.indexOf('#list-') + 6);

That worked fine in FireFox but not in IE. So I tried a few other:

这在 FireFox 中运行良好,但在 IE 中不起作用。所以我尝试了其他一些:

//ui.tab.parentNode.setAttribute('id', ui.tab.href.substring(ui.tab.href.indexOf('#list-') + 6));
//$(ui.tab.parentNode).attr({'id':ui.tab.href.substring(ui.tab.href.indexOf('#list-') + 6)});
//ui.tab.parentNode.id.value = ui.tab.href.substring(ui.tab.href.indexOf('#list-') + 6);

None of them worked! So after a few hours of test and Googeling I gave up and draw the conclusion that IE cant set the ID attribute of an element dynamically.

他们都没有工作!所以经过几个小时的测试和谷歌搜索我放弃并得出结论,IE无法动态设置元素的ID属性。

As I sad this is probably not relevant to your issue but I thought I would share.

令我难过的是,这可能与您的问题无关,但我想我会分享。

Solution

解决方案

And for all of you who found this by Googleing on the tabs issue I had here is what I ended up doing in the tabsremove callback to solve the issue:

对于所有通过 Google 搜索标签问题发现此问题的人,我在这里遇到的是我最终在 tabsremove 回调中解决问题的方法:

var dbIndex = event.currentTarget.offsetParent.childNodes[0].href.substring(event.currentTarget.offsetParent.childNodes[0].href.indexOf('#list-') + 6);

Probably not the sexiest solution but hey it solved the issue. If anyone have any input please share...

可能不是最性感的解决方案,但嘿它解决了这个问题。如果有人有任何意见,请分享...