简体   繁体   English

Javascript IE innerHTML <select>

[英]Javascript IE innerHTML of <select>

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. 我有正确抓取当前值的JavaScript,一切正常在Firefox,Safari,Chrome和Opera中正常工作。 IE is a pain. 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>');
}

Well, first of all you have a closing tag for the select that you try to put inside the select element, which makes the code invalid. 好吧,首先,你有一个关于你试图放入select元素的select的结束标记,这会使代码无效。

Then there might be a problem with how the select element treats it's content. 那么select元素如何处理它的内容可能会有问题。 When the HTML code is parsed, the select element doesn't have any child elements, like a regular element does. 解析HTML代码时, select元素没有任何子元素,就像常规元素一样。 Instead the options are items in it's options collection. 相反,选项是其options集合中的项目。

If you want to change the items in the select element, change the content of it's option collection. 如果要更改select元素中的项目,请更改其option集合的内容。 Ie to add items, create option objects using the document.createElement method and add to the collection. 即添加项目,使用document.createElement方法创建option对象并添加到集合中。 Example: 例:

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

You have to remove the "select"-Element and the end of setting the innerHTML-Property. 您必须删除“select”-Element并设置innerHTML-Property的结束。 This is not a part of innerHTML. 这不是innerHTML的一部分。 Its the end-tag of the element 'bandwith' itself. 它是'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>');

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. 这是我遇到的一个方便的黑客,它可以在FF和IE中工作,作为无法在select元素上更改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>');
}

I recently came across this problem with IE. 我最近遇到了IE的这个问题。 I came up with a turnkey solution that works with the following things in mind: 我想出了一个可以满足以下要求的交钥匙解决方案:

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

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: 现在执行select对象和字符串值中的函数传递:

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: 如果您需要脚本来REPLACE值,请使用以下命令:

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! 我希望这有助于其他人!

The real cause of the problem is that due to a DOM parsing/updating problem, IE will not insert child option elements into a select element. 问题的真正原因是由于DOM解析/更新问题,IE不会将子option元素插入到select元素中。 Even IE9 still has this problem (later versions not checked). 即使IE9仍然存在此问题(未检查更高版本)。

You have to put the select in a div or span and replace the whole select . 您必须将select放在divspan并替换整个select Below you will find an example that shows that then IE will play ball as well. 下面你会看到一个例子,表明IE也会玩球。 Because this innerHTML problem generally occurs when dynamically generating selects, I made an AJAX & PHP example. 因为这个innerHTML问题通常在动态生成选择时出现,所以我做了一个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. 在本演示中,请务必仅选择黄色背景的选项。

使用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>');

A quick search shows this has been a known bug in IE since at least IE5 . 快速搜索显示,至少从IE5开始,这已成为IE中的一个已知错误。 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). 您可以尝试使用createElement并make选项并附加到select对象,或使用类似jQuery的库并将html附加到节点(必须处理在IE中工作所必需的魔法)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM