简体   繁体   English

Javascript 对象和 Internet Explorer

[英]Javascript objects and internet explorer

I have this code:我有这个代码:

 jsonObj = [];
 $("#test").find('.data').each(function() {

    var description = $(this).find('.description').val();
    var food = $(this).find('.food').val();

    item = {}
    item ["description"] = description;
    item ["food"] = food;

    jsonObj.push(item);
});

Internet explorer 11 inserts empty/null values. Internet Explorer 11 插入空/空值。 of-course it works well in chrome firefox or even in edge当然,它在 Chrome Firefox 甚至 Edge 中运行良好

I can replicate the issue using your code in this fiddle in IE11.我可以在 IE11 的这个小提琴中使用你的代码复制这个问题。

The problem is that you haven't declared item , and so you're using a global item (thanks to The Horror of Implicit Globals 1 ), which is predefined in IE11 as a native function you can't overwrite or add properties to (this one , according tothis page ).问题是您尚未声明item ,因此您使用的是全局item (感谢隐式全局的恐怖1 ),它在 IE11 中预定义为本机函数,您无法覆盖或添加属性到(这个,根据这个页面)。 It's not predefined (or is overwritable) in other browsers.它在其他浏览器中不是预定义的(或可覆盖的)。

The lesson here is: Declare your variables .这里的教训是:声明你的变量 :-) If you do that, it works on IE11 as well ( updated fiddle ): :-) 如果你这样做,它也适用于 IE11(更新小提琴):

 var jsonObj = []; // *** $("#test").find('.data').each(function() { var description = $(this).find('.description').val(); var food = $(this).find('.food').val(); var item = {} // *** item ["description"] = description; item ["food"] = food; jsonObj.push(item); }); $("<pre>").text("Result: " + JSON.stringify(jsonObj, null, 2)).appendTo(document.body);
 <div id="test"> <div class="data"> <input type="text" class="description" value="description1"> <input type="text" class="food" value="food1"> </div> <div class="data"> <input type="text" class="description" value="description2"> <input type="text" class="food" value="food2"> </div> <div class="data"> <input type="text" class="description" value="description3"> <input type="text" class="food" value="food3"> </div> </div> <script src="https://code.jquery.com/jquery-3.1.1.js"></script>


1 That's a post on my anemic little blog. 1那是我贫血的小博客上的一篇文章。

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

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