【问题标题】:How do you dynamically create a radio button in Javascript that works in all browsers?如何在 Javascript 中动态创建适用于所有浏览器的单选按钮?
【发布时间】:2010-09-12 05:35:42
【问题描述】:

使用例如动态创建单选按钮

var radioInput = document.createElement('input');
radioInput.setAttribute('type', 'radio');
radioInput.setAttribute('name', name);

在 Firefox 中有效,但在 IE 中无效。为什么不呢?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    按照 Patrick 的建议,使用临时节点我们可以摆脱 try/catch:

    function createRadioElement(name, checked) {
        var radioHtml = '<input type="radio" name="' + name + '"';
        if ( checked ) {
            radioHtml += ' checked="checked"';
        }
        radioHtml += '/>';
    
        var radioFragment = document.createElement('div');
        radioFragment.innerHTML = radioHtml;
    
        return radioFragment.firstChild;
    }
    

    【讨论】:

      【解决方案2】:

      根据这篇文章及其 cmets: http://cf-bill.blogspot.com/2006/03/another-ie-gotcha-dynamiclly-created.html

      以下作品。显然问题是您不能在 IE 中动态设置 name 属性。我还发现你也不能动态设置checked属性。

      function createRadioElement( name, checked ) {
          var radioInput;
          try {
              var radioHtml = '<input type="radio" name="' + name + '"';
              if ( checked ) {
                  radioHtml += ' checked="checked"';
              }
              radioHtml += '/>';
              radioInput = document.createElement(radioHtml);
          } catch( err ) {
              radioInput = document.createElement('input');
              radioInput.setAttribute('type', 'radio');
              radioInput.setAttribute('name', name);
              if ( checked ) {
                  radioInput.setAttribute('checked', 'checked');
              }
          }
      
          return radioInput;
      }
      

      【讨论】:

        【解决方案3】:

        这是一个更通用的解决方案示例,它预先检测 IE 并处理 IE 也有问题的其他属性,摘自DOMBuilder

        var createElement = (function()
        {
            // Detect IE using conditional compilation
            if (/*@cc_on @*//*@if (@_win32)!/*@end @*/false)
            {
                // Translations for attribute names which IE would otherwise choke on
                var attrTranslations =
                {
                    "class": "className",
                    "for": "htmlFor"
                };
        
                var setAttribute = function(element, attr, value)
                {
                    if (attrTranslations.hasOwnProperty(attr))
                    {
                        element[attrTranslations[attr]] = value;
                    }
                    else if (attr == "style")
                    {
                        element.style.cssText = value;
                    }
                    else
                    {
                        element.setAttribute(attr, value);
                    }
                };
        
                return function(tagName, attributes)
                {
                    attributes = attributes || {};
        
                    // See http://channel9.msdn.com/Wiki/InternetExplorerProgrammingBugs
                    if (attributes.hasOwnProperty("name") ||
                        attributes.hasOwnProperty("checked") ||
                        attributes.hasOwnProperty("multiple"))
                    {
                        var tagParts = ["<" + tagName];
                        if (attributes.hasOwnProperty("name"))
                        {
                            tagParts[tagParts.length] =
                                ' name="' + attributes.name + '"';
                            delete attributes.name;
                        }
                        if (attributes.hasOwnProperty("checked") &&
                            "" + attributes.checked == "true")
                        {
                            tagParts[tagParts.length] = " checked";
                            delete attributes.checked;
                        }
                        if (attributes.hasOwnProperty("multiple") &&
                            "" + attributes.multiple == "true")
                        {
                            tagParts[tagParts.length] = " multiple";
                            delete attributes.multiple;
                        }
                        tagParts[tagParts.length] = ">";
        
                        var element =
                            document.createElement(tagParts.join(""));
                    }
                    else
                    {
                        var element = document.createElement(tagName);
                    }
        
                    for (var attr in attributes)
                    {
                        if (attributes.hasOwnProperty(attr))
                        {
                            setAttribute(element, attr, attributes[attr]);
                        }
                    }
        
                    return element;
                };
            }
            // All other browsers
            else
            {
                return function(tagName, attributes)
                {
                    attributes = attributes || {};
                    var element = document.createElement(tagName);
                    for (var attr in attributes)
                    {
                        if (attributes.hasOwnProperty(attr))
                        {
                            element.setAttribute(attr, attributes[attr]);
                        }
                    }
                    return element;
                };
            }
        })();
        
        // Usage
        var rb = createElement("input", {type: "radio", checked: true});
        

        完整的 DOMBuilder 版本还处理事件侦听器注册和子节点的规范。

        【讨论】:

          【解决方案4】:

          我个人不会自己创建节点。正如您所注意到的,浏览器特有的问题太多了。通常我使用来自script.aculo.usBuilder.node。使用这个你的代码会变成这样:

          Builder.node('input', {type: 'radio', name: name})
          

          【讨论】:

            【解决方案5】:

            我的解决方案:

            html
                head
                    script(type='text/javascript')
                        function createRadioButton()
                        {
                           var newRadioButton
                             = document.createElement(input(type='radio',name='radio',value='1st'));
                           document.body.insertBefore(newRadioButton);
                        }
                body
                    input(type='button',onclick='createRadioButton();',value='Create Radio Button')
            

            【讨论】:

              【解决方案6】:

              在 javascript 中动态创建单选按钮:

              <%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”RadioDemo.aspx.cs” Inherits=”JavascriptTutorial.RadioDemo” %>
              
              <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
              
              <html xmlns=”http://www.w3.org/1999/xhtml”>
              <head runat=”server”>
              <title></title>
              <script type=”text/javascript”>
              
              /* Getting Id of Div in which radio button will be add*/
              var containerDivClientId = “<%= containerDiv.ClientID %>”;
              
              /*variable count uses for define unique Ids of radio buttons and group name*/
              var count = 100;
              
              /*This function call by button OnClientClick event and uses for create radio buttons*/
              function dynamicRadioButton()
              {
              /* create a radio button */
              var radioYes = document.createElement(“input”);
              radioYes.setAttribute(“type”, “radio”);
              
              /*Set id of new created radio button*/
              radioYes.setAttribute(“id”, “radioYes” + count);
              
              /*set unique group name for pair of Yes / No */
              radioYes.setAttribute(“name”, “Boolean” + count);
              
              /*creating label for Text to Radio button*/
              var lblYes = document.createElement(“lable”);
              
              /*create text node for label Text which display for Radio button*/
              var textYes = document.createTextNode(“Yes”);
              
              /*add text to new create lable*/
              lblYes.appendChild(textYes);
              
              /*add radio button to Div*/
              containerDiv.appendChild(radioYes);
              
              /*add label text for radio button to Div*/
              containerDiv.appendChild(lblYes);
              
              /*add space between two radio buttons*/
              var space = document.createElement(“span”);
              space.setAttribute(“innerHTML”, “&nbsp;&nbsp”);
              containerDiv.appendChild(space);
              
              var radioNo = document.createElement(“input”);
              radioNo.setAttribute(“type”, “radio”);
              radioNo.setAttribute(“id”, “radioNo” + count);
              radioNo.setAttribute(“name”, “Boolean” + count);
              
              var lblNo = document.createElement(“label”);
              lblNo.innerHTML = “No”;
              containerDiv.appendChild(radioNo);
              containerDiv.appendChild(lblNo);
              
              /*add new line for new pair of radio buttons*/
              var spaceBr= document.createElement(“br”);
              containerDiv.appendChild(spaceBr);
              
              count++;
              return false;
              }
              </script>
              </head>
              <body>
              <form id=”form1″ runat=”server”>
              <div>
              <asp:Button ID=”btnCreate” runat=”server” Text=”Click Me” OnClientClick=”return dynamicRadioButton();” />
              <div id=”containerDiv” runat=”server”></div>
              </div>
              </form>
              </body>
              </html>
              

              (source)

              【讨论】:

              • 单独的链接是considered a poor answer,因为它本身没有意义,并且不能保证目标资源在未来仍然存在。请尝试至少包含您要链接的信息的摘要。
              • containerDivClientId 被使用了吗?
              【解决方案7】:
              for(i=0;i<=10;i++){
                 var selecttag1=document.createElement("input");
                 selecttag1.setAttribute("type", "radio");
                 selecttag1.setAttribute("name", "irrSelectNo"+i);
                 selecttag1.setAttribute("value", "N");
                 selecttag1.setAttribute("id","irrSelectNo"+i);
              
                 var lbl1 = document.createElement("label");
                 lbl1.innerHTML = "YES";
                 cell3Div.appendChild(lbl);
                 cell3Div.appendChild(selecttag1);
              }
              

              【讨论】:

              • 欢迎来到stackoverflow。考虑为您的答案添加解释。
              【解决方案8】:

              快速回复旧帖:

              Roundcrisis 的上述帖子很好,如果且仅当,您知道将预先使用的单选/复选框控件的数量。在某些情况下,通过“动态创建单选按钮”这一主题来解决,用户需要的控件数量是未知的。此外,我不建议“跳过”“try-catch”错误捕获,因为这样可以轻松捕获可能不符合当前标准的未来浏览器实现。在这些解决方案中,我建议使用 Patrick Wilkes 在回答他自己的问题时提出的解决方案。

              为了避免混淆,这里重复一遍:

              function createRadioElement( name, checked ) {
                 var radioInput;
                 try {
                      var radioHtml = '<input type="radio" name="' + name + '"';
                      if ( checked ) {
                          radioHtml += ' checked="checked"';
                      }
                      radioHtml += '/>';
                      radioInput = document.createElement(radioHtml);
                  } catch( err ) {
                      radioInput = document.createElement('input');
                      radioInput.setAttribute('type', 'radio');
                      radioInput.setAttribute('name', name);
                      if ( checked ) {
                          radioInput.setAttribute('checked', 'checked');
                      }
                  }
                  return radioInput;}
              

              【讨论】:

                【解决方案9】:

                Patrick 的回答有效,或者您也可以设置“defaultChecked”属性(这将在 IE 中适用于 radio 或 checkbox 元素,并且不会在其他浏览器中导致错误。

                PS 此处列出了您无法在 IE 中设置的属性的完整列表:

                http://webbugtrack.blogspot.com/2007/08/bug-242-setattribute-doesnt-always-work.html

                【讨论】:

                  【解决方案10】:

                  为什么不创建输入,将样式设置为显示:无,然后在需要时更改显示 这样你也可以更好地处理没有 js 的用户。

                  【讨论】:

                    【解决方案11】:

                    我的建议是不要使用 document.Create()。更好的解决方案是构建未来控件的实际 HTML,然后将其像 innerHTML 一样分配给某个占位符 - 它允许浏览器自己呈现它,这比任何 JS DOM 操作都要快。

                    干杯。

                    【讨论】:

                      猜你喜欢
                      • 2014-07-08
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 2018-07-14
                      • 2021-04-13
                      • 2017-01-26
                      • 2011-05-29
                      相关资源
                      最近更新 更多