<select> 的 Javascript IE innerHTML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3496797/
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-10-25 01:20:50  来源:igfitidea点击:

Javascript IE innerHTML of <select>

javascripthtmlinternet-explorerformsinnerhtml

提问by Xavias

I'm trying to change the innerHTML of a element based on the value of the previous element.

我正在尝试根据前一个元素的值更改元素的 innerHTML。

I have the javascript correctly grabbing the current value and everything works correctly in Firefox, Safari, Chrome and Opera. IE is a pain.

我让 javascript 正确获取当前值,并且在 Firefox、Safari、Chrome 和 Opera 中一切正常。IE是一种痛苦。

sample code:

示例代码:

<form action="soap.php" method="post">
    <select name="circuitproduct" id="circuitproduct" onchange="bandwidthfunction();">
        <option>Dedicated Voice</option>
        <option>Frame Relay</option>
        <option>ATM</option>
        <option>Dedicated Internet</option>
        <option>IP Solutions Private Port</option>
        <option>IP Solutions Enhanced Port</option>
        <option>Private Line – Domestic</option>
        <option>Int'l Private Line</option>
        <option>Qwest Metro Private Line (QMPL)</option>
        <option>Qwest Metro Ethernet Private Line (QMEPL)</option>
    </select><br />
    <select name="term" id="term">
        <option value="1-Year">1-Year</option>
        <option value="2-Year">2-Year</option>
        <option value="3-Year">3-Year</option>
    </select>
    <select id="bandwidth">
    </select>
    <select id="sublooptype">
    </select>
</form>

sample javascript:

示例javascript:

function bandwidthfunction() {
var product = document.getElementById('circuitproduct').value;
    if (product == 'Dedicated Voice') {
        document.getElementById('bandwidth').innerHTML = ('<option value="DS-1">DS-1</option><option value="DS-3">DS-3</option><option value="OC-3">OC-3</option><option value="OC-12">OC-12</option>');
        document.getElementById('sublooptype').innerHTML = ('<option value="Special Access">Special Access</option><option>CO MtPt - Special Access</option><option>CPA Special Access</option>');
    }
    else if (product == 'Frame Relay') {
        document.getElementById('bandwidth').innerHTML = ('<option value="DS-1">DS-1</option><option value="DS-3">DS-3</option><option value="OC-3">OC-3</option><option value="OC-12">OC-12</option>');
        document.getElementById('sublooptype').innerHTML = ('<option value="Special Access">Special Access</option><option>CO MtPt - Special Access</option><option>CPA Special Access</option>');
}

回答by Guffa

Well, first of all you have a closing tag for the selectthat you try to put inside the selectelement, which makes the code invalid.

好吧,首先你有一个结束标签select,你试图把它放在select元素中,这会使代码无效。

Then there might be a problem with how the selectelement treats it's content. When the HTML code is parsed, the selectelement doesn't have any child elements, like a regular element does. Instead the options are items in it's optionscollection.

那么select元素如何处理它的内容可能会有问题。解析 HTML 代码时,该select元素没有任何子元素,就像常规元素一样。相反,选项是它的options集合中的项目。

If you want to change the items in the selectelement, change the content of it's optioncollection. I.e. to add items, create optionobjects using the document.createElementmethod and add to the collection. Example:

如果要更改select元素中的项目,请更改其option集合的内容。即添加项目,option使用该document.createElement方法创建对象并添加到集合中。例子:

var opt = document.createElement('OPTION');
opt.text = 'Choose me';
opt.value = 42;
document.getElementById('bandwidth').options.add(opt);

回答by cpt.oneeye

You have to remove the "select"-Element and the end of setting the innerHTML-Property. This is not a part of innerHTML. Its the end-tag of the element 'bandwith' itself.

您必须删除“select”-Element 和设置innerHTML-Property 的结尾。这不是innerHTML 的一部分。它是元素“bandwith”本身的结束标记。

document.getElementById('bandwidth').innerHTML = ('<option value="DS-1">DS-1</option><option value="DS-3">DS-3</option><option value="OC-3">OC-3</option><option value="OC-12">OC-12</option>');

回答by Tyler W. Cox

Here's a handy hack I came across that works in both FF and IE as a workaround to the inability to change innerHTML on select elements.

这是我遇到的一个方便的 hack,它在 FF 和 IE 中都有效,作为无法在选择元素上更改 innerHTML 的解决方法。

document.getElementById('bandwidth').outerHTML = document.getElementById('bandwidth').outerHTML.replace( document.getElementById('bandwidth').innerHTML + '</select>' , '<option value="DS-1">DS-1</option><option value="DS-3">DS-3</option><option value="OC-3">OC-3</option><option value="OC-12">OC-12</option>' + '</select>' );

or as a function for readability:

或作为可读性的函数:

function swapInnerHTML(objID,newHTML) {
  var el=document.getElementById(objID);
  el.outerHTML=el.outerHTML.replace(el.innerHTML+'</select>',newHTML+'</select>');
}

回答by Eko3alpha

I recently came across this problem with IE. I came up with a turnkey solution that works with the following things in mind:

我最近在 IE 上遇到了这个问题。我想出了一个交钥匙解决方案,考虑到以下几点:

  • You don't want to use jQuery
  • Need it to work in IE < 9
  • You want to append ( not replace the existing options ) string options into an existing select element
  • The select must be a type of "select-one"
  • Must wrap selects in their own parent element
  • 你不想使用jQuery
  • 需要它在 IE < 9 中工作
  • 您想将(而不是替换现有选项)字符串选项附加到现有选择元素中
  • 选择必须是“select-one”类型
  • 必须将选择包裹在它们自己的父元素中

We have many landing pages requesting the same information (age, products, country, state etc... ) but with different select options. The implementation I use appends new select options. This was done to allow a custom default option per lading page. One page may have the first option as "select item" another may have "choose one" and so forth.

我们有许多登陆页面要求相同的信息(年龄、产品、国家、州等...),但有不同的选择选项。我使用的实现附加了新的选择选项。这样做是为了允许每个提货页有一个自定义的默认选项。一个页面可能有第一个选项作为“选择项目”,另一个页面可能有“选择一个”等等。

Select format:

选择格式:

<div>  <!-- you MUST wrap the select in a tag without any siblings -->
    <select name="age" id="form-age">
        <option value="">Choose Age</option>
    </select>
</div>  <!-- you MUST wrap the select in a tag without any siblings -->

Here is the function to APPEND/ADD values:

这是 APPEND/ADD 值的函数:

function addOptions(el, options){
    // checks to make sure element exists and is a select
    if(el && el.type === "select-one"){
        el.innerHTML = el.innerHTML + options;
        el.parentNode.innerHTML = el.outerHTML; // needed for IE
    }
}

Now to execute the function pass in the select object and string values:

现在执行传入选择对象和字符串值的函数:

addOptions(
    document.getElementById("form-age"), 
    '<option value="1">18-25</option><option value="2">26-35</option><option value="3">36-45</option><option value="4">46-55</option><option value="5">56-65</option><option value="6">66-75</option><option value="7">76-85</option><option value="8">86+</option>'
);

This will generate a select with the options passed, even in IE!

这将生成一个带有传递选项的选择,即使在 IE 中!

<div>  <!-- you MUST wrap the select in a tag without any siblings -->
    <select name="age" id="form-age">
        <option value="">Choose Age</option>
        <option value="1">18-25</option><option value="2">26-35</option><option value="3">36-45</option><option value="4">46-55</option><option value="5">56-65</option><option value="6">66-75</option><option value="7">76-85</option><option value="8">86+</option>
    </select>
</div>  <!-- you MUST wrap the select in a tag without any siblings -->

If you needed the script to REPLACE the values use the following:

如果您需要脚本来替换这些值,请使用以下内容:

function replaceOptions(el, options){
    if(el && el.type === "select-one"){
        el.innerHTML = options;
        el.parentNode.innerHTML = el.outerHTML; // needed for IE
    }
}

I hope this helps someone else!

我希望这对其他人有帮助!

回答by John Hoven

A quick search shows this has been a known bug in IE since at least IE5. You could try to use createElement and make options and append to the select object, or use a library like jQuery and append the html to the node (which must take care of the magic necessary to work in IE).

快速搜索表明,至少从 IE5 开始,这是 IE 中的一个已知错误。您可以尝试使用 createElement 和 make options 并附加到选择对象,或者使用像 jQuery 这样的库并将 html 附加到节点(它必须处理在 IE 中工作所需的魔法)。

回答by Frank Conijn

The real cause of the problem is that due to a DOM parsing/updating problem, IE will not insert child optionelements into a selectelement. Even IE9 still has this problem (later versions not checked).

问题的真正原因是由于DOM解析/更新问题,IE不会将子option元素插入select元素中。连IE9也有这个问题(后面的版本没查)。

You have to put the selectin a divor spanand replace the whole select. Below you will find an example that shows that then IE will play ball as well. Because this innerHTML problem generally occurs when dynamically generating selects, I made an AJAX & PHP example.

你必须把select一个divspan和更换整个select。您将在下面找到一个示例,该示例表明 IE 也会打球。因为这个innerHTML问题一般在动态生成select的时候会出现,所以我做了一个AJAX & PHP的例子。

The html file:

html文件:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Chain(ed) select with AJAX and PHP</title>
<style>
    select {
    min-width: 170px;
    }
    option.toSelect {
    background: yellow;
    }
</style>
</head>
<body>
    <form action="whatever.php">
        <span>
            <select id="cities" onchange="getOptions(this.value,'airlinesContainer')">
                <option value="">Select a city:</option>
                <option value="boston_airlines">Boston</option>
                <option value="chicago_airlines" class="toSelect">Chicago</option>
                <option value="newyork_airlines">New York</option>
            </select>
        </span>
        <span id="airlinesContainer">
            <select>
            </select>
        </span>
        <span id="classesContainer">
            <select>
            </select>
        </span>
    </form>
    <script>
        function getOptions(qValue,containerId) {
            var ajaxRequest = new XMLHttpRequest();
            if ((qValue == "") || (containerId == "")) {
                alert('Invalid selection.');
                return;
            }
            ajaxRequest.onreadystatechange = function() {
                if ((ajaxRequest.readyState == 4) && (ajaxRequest.status == 200)) {
                    document.getElementById(containerId).innerHTML = ajaxRequest.responseText;
                }
            }
            ajaxRequest.open("GET","getoptions.php?q="+qValue,true);
            ajaxRequest.send();
        }
    </script>
</body>
</html>

.

.

And the php file, which should be named 'getoptions.php' and should be put in the same folder:

和 php 文件,它应该被命名为“getoptions.php”并且应该放在同一个文件夹中:

<?php
$q = $_GET['q'];

$chicago_airlines ='
            <select id="airlines" onchange="getOptions(this.value,\'classesContainer\')">
                <option value="">Select an airline:</option>
                <option value="delta_classes">Delta</option>
                <option value="klm_classes" class="toSelect">KLM</option>
                <option value="united_classes">United Airlines</option>
            </select>';

$klm_classes ='
            <select id="classes">
                <option value="business">World Business Class</option>
                <option value="comfort">Economy Comfort</option>
                <option value="economy">Economy</option>
            </select>';

if ($q == 'chicago_airlines') {
    echo $chicago_airlines;
}
elseif ($q == 'klm_classes') {
    echo $klm_classes;
}
else {
    echo '<select>
              <option>Invalid selection</option>
          </select>';
}
?>

.

.

Be sure to select only the options with a yellow background, in this demo.

在此演示中,请务必仅选择黄色背景的选项。

回答by John Adel

use Jquery

使用jQuery

$('#bandwidth').html('<option value="DS-1">DS-1</option><option value="DS-3">DS-3</option><option value="OC-3">OC-3</option><option value="OC-12">OC-12</option>');

$('#bandwidth').html('<option value="DS-1">DS-1</option><option value="DS-3">DS-3</option><option value="OC-3">OC-3</option><option value="OC-12">OC-12</option>');