使用jQuery排序,删除和追加元素在IE中不起作用
This function that sorts my links works like a charm on Chrome/Safari/Firefox but not in IE. Can someone tell me why?
此功能可以对我的链接进行排序,就像Chrome / Safari / Firefox上的魅力一样,但在IE中则不然。有人可以告诉我为什么吗?
Symptom: everything disappears (line2) nothing appears (line3)
症状:一切都消失了(第2行)没有出现任何内容(第3行)
HTML:
HTML:
<div class="genres"> <a title="90 items" href="?genre=absurdism"><span>absurdism</span></a> <a title="83 items" href="?genre=action"><span>action</span></a> <a title="322 items" href="?genre=adult"><span>adult</span></a> <a title="2974 items" href="?genre=adventure"><span>adventure</span></a> <a title="106 items" href="?genre=about+comics"><span>about comics</span></a> </div>
SCRIPT:
脚本:
sorted = $('.genres a').sort(function(a, b) {
return a.innerHTML > b.innerHTML
});
$('.genres').html('');
sorted.each(function(i, a) {
$('.genres').append(a)
});
Fiddle: http://jsfiddle.net/MWkJg/2/
小提琴:http://jsfiddle.net/MWkJg/2/
The online page of this code is on http://www.lambiek.net/webshop.html (click on "genre" button)
此代码的在线页面位于http://www.lambiek.net/webshop.html(点击“流派”按钮)
2 个解决方案
#1
4
You need to replace this:
你需要替换这个:
$('.genres').html('');
with
同
$('.genres').empty();
html
uses the innerHTML
property to remove contents, and this is handled inconsistently among browsers as you have just seen. empty
, however, uses the removeChild
method, and works consistently across browsers. (Incidentally jQuery 2.0 uses textContent
.)
html使用innerHTML属性来删除内容,并且如您所见,这在浏览器之间处理不一致。但是,empty使用removeChild方法,并且跨浏览器一致地工作。 (顺便说一句,jQuery 2.0使用textContent。)
Also, for your sort
method to work consistently, it needs to return a numeric value:
此外,为使您的排序方法始终如一地工作,它需要返回一个数值:
var sorted = $('.genres a').sort(function(a, b) {
return a.innerHTML < b.innerHTML ? -1 :
a.innerHTML === b.innerHTML ? 0 :
1;
});
FIDDLE
小提琴
更多相关文章
- 如何在Safari浏览器中禁用Ajax缓存?
- IE 浏览器各个版本 JavaScript 支持情况一览表
- 我可以禁用“后退”按钮浏览器功能吗?
- 浏览器如何处理HTML元素上的无效/未指定的属性?
- JQuery纯前端导入Excel文件,兼容IE10及IE9版本以下浏览器处理方法
- 删除复制+粘贴的富文本格式? (跨浏览器)
- 如何执行浏览器内对比扩展/规范化?
- 浏览器环境下JavaScript脚本加载与执行探析之动态脚本与Ajax脚本
- js获取点击事件的位置,兼容主流浏览器