简体   繁体   中英

Why does this Javascript work in Firefox, but not Internet Explorer?

  <img src="images/butAdd.png" onclick="addField(1,1);" />

  <div id="divField"></div>
  <script type="text/javascript">
    function addField(count, type) {
        var bid = document.getElementById("bid").value;
        $("#divField").append("<a href='#' onClick='javascript:removeField(\"#bow" + bid + "\"); return false;'><img src='images/closeSmall.png' /></a>");  
        }

    function removeField(bid) {
        $(bid).remove();
    }
 </script>

Consider this Javascript code that works fine in Firefox, but not in Internet Explorer.

The function addField() works, but removeField() does not.

Any ideas on why this wouldn't work, or any workarounds?

Try this one.

function addField(count, type) {
                            $("#divField").append("<a href='#' onClick='javascript:removeField(); return false;'><img src='images/closeSmall.png' /></a>");      
                    }

                    function removeField() {
                            $("#bid").remove();
                    }

onclick event should not have 'javascript:' in front of code. Such string should be only when you use 'href=' to put JS code.

I think it is do with the variable called 'bid'. The value for the variable is assigned only when you are calling the addField() and it is local to that method.

In removeField() the value for 'bid' is undefined, that is why it is not working.

Try changing the removeField() like this

function removeField() {
    var bid = document.getElementById("bid").value;
    $(bid).remove();
}

Your addFiled can look like:

$("<a href='#'><img src='images/closeSmall.png' /></a>").appendTo("#divField")
  .click(function() {
    $("#bid").remove();
  })

try changing:

var bid = document.getElementById("bid").value;

to

var bid = $("#bid").val();

I think there is a quirk in the way IE does the .value vs firefox

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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