【问题标题】:This code works in all other browsers except in IE此代码适用于除 IE 之外的所有其他浏览器
【发布时间】:2014-01-10 23:22:08
【问题描述】:

这在除 IE 之外的所有浏览器中都可以正常工作,任何人都可以解释原因,以便我可以修复它。我正在根据我的下拉列表中所选索引的索引显示 javascript 对象的索引

 $(document).ready(function () {
var pdata = [{ Name: "Apples", Price: 1.99 },{ Name: "Bananas", Price: 2.45 } ];

    $('#produceTMPL').tmpl(pdata).appendTo('#produceList');

      $(document).ready(function () {


      $('#add1').click(function () {
        var selected = $('#produceList option:selected').index();

        item = pdata[selected];

        console.log(selected);
        $('#cart').append('<p>' + item.Name + ', ' + item.Price + '</p>');




    });  
    });

HTML:

     <div>
  <select id="produceList">
  <option>make a selection</option>
  </select>

【问题讨论】:

  • 您是否打开了 Web 开发者控制台? F12
  • 这在 IE 中如何“不起作用”?哪个版本的IE?它做什么?您在控制台中看到任何错误吗?
  • 为什么$(document).ready(function () { 中有一个$(document).ready(function () {
  • 您真的需要 2 个文档就绪调用吗?此外,如果您尝试运行控制台,旧版本的 IE 可能会哭泣
  • 尝试打开控制台,然后重新加载您的页面,看看它是否有效。 console.log 不能在 IE 中工作,除非控制台打开。

标签: javascript jquery


【解决方案1】:

item 是 IE 中窗口对象的受保护属性。只需重命名您的变量,或在您的函数中正确声明它(使用var)。

【讨论】:

    【解决方案2】:

    console.log 在 IE 中抛出错误,所以为了安全起见,不要在不检查浏览器是否支持的情况下使用 console.log。

    try{
        if(console && console.log) console.log('message')   
    }catch(e){}
    

     if ('undefined' !== typeof console){console.log(message); }
    

    【讨论】:

    • IE 支持console.log。只需打开控制台(开发工具)即可。您需要打开开发工具,然后重新加载页面。
    • 这就是为什么我建议打开它然后重新加载页面。
    • 但在 IE 中它在我的 html 上显示未定义
    • @RocketHazmat 我知道,但我想说的是没有人首先打开它,此时不支持 console.log,如果你想避免这种情况,在盲目使用该功能之前进行检查。
    • @Rao:很公平:-)
    猜你喜欢
    • 2011-06-30
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-10
    • 1970-01-01
    相关资源
    最近更新 更多