[英]How to call JavaScript methods on jQuery objects
让我们直接说清楚。
不幸的是,以下代码必须在IE8上运行。
应该找到与当前页面的URL与nav中存在的<a>
标记的href
属性匹配的URL。 然后,将该标记的类not-selected
交换为selected
或者默认将其转换为第一个<a>
标记。
的HTML
<ul id="nav">
<li><a class="not-selected" href="index.php"><span>Index Page</span></a></li>
<li>
<a class="not-selected" href="page1.php"><span>Page 1</span></a>
</li>
<li>
<a class="not-selected" href="page2.php"><span>Page 2</span></a>
</li>
</ul>
JavaScript(jQuery)
var url = $(document).attr('URL');
var isIndexPage = true;
var menu = $('#nav').children('li');
var anchors = menu.find('a');
anchors.each(function(index) {
// Is the href the same as the page?
if ($(this).href != null && anchor.href == url)
{
$(this).first().addClass('selected');
if ($(this).className.match(/\bnot\-selected\b/))
$(this).first().removeClass('not-selected');
indexPage = false;
}
else
{
// remove class="selected" if it has that class
if ($(this).className.match(/\bselected\b/))
{
$(this).first().removeClass('selected');
}
// Add class="trigger"
$(this).first().addClass('not-selected');
}
});
if (isIndexPage)
{
menu[0].childNodes[0].setAttribute('class', 'selected');
}
在脚本上,我在调用className
属性(应为字符串)的match()
函数的行上收到错误消息。
这是为什么?
如何使用可在IE8上使用的jQuery或JavaScript修复它?
先感谢您。
className
是HTML元素的本机属性,而您试图将其作为jQuery对象的属性来调用。 执行以下任一操作:
$(this)[0].className
要么
$(this).attr('class')
旁注:您不是首先要检查元素是否具有类,而是假设它具有类。 如果元素没有class
属性,则第二种(jQuery)方法将出错,因为如果没有class
属性,它将返回null
(与本机className
属性相反,它在没有相应class
属性的情况下默认为空字符串)。
你可以更换线
if ($(this).className.match(/\bselected\b/))
有了这个
if ($(this).hasClass('selected'));
这要简单得多。 对于“未选中”类也是如此。
jQuery对象没有className
属性,可以使用hasClass
方法检查元素是否具有类:
if ($(this).hasClass('not-selected'))
但是,您根本不需要该检查。 您可以只删除该类,并且如果该类不存在,则该调用将不执行任何操作。 您可以这样做:
$(this).addClass('selected').removeClass('not-selected');
同样,在else
块中,您无需检查,只需删除并添加:
$(this).removeClass('selected').addClass('not-selected');
实际上,您甚至不需要if
,您可以使用toggleClass
和一个布尔值来实现。 这将是您的整个循环:
anchors.each(function() {
var sel = $(this).href != null && $(this).href == url;
$(this).toggleClass('selected', sel).toggleClass('not-selected', !sel);
});
另外,您在使用未定义的变量anchor
时应使用$(this)
。 更改此行:
if ($(this).href != null && anchor.href == url)
至:
if ($(this).href != null && $(this).href == url)
我认为您应该对网址使用普通的JS,对于其余示例,请使用jQuery:
的JavaScript
var path = window.location.pathname;
$.each($('#nav li a'), function(index, anchor) {
if(path.indexOf($(anchor).attr('href')) != -1) {
$('#nav li a').removeClass('selected');
$(anchor).addClass('selected').removeClass('not-selected');
}
});
这是一个示例: http : //jsfiddle.net/2rSqL/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.