【发布时间】:2015-07-22 17:48:02
【问题描述】:
我想更改用于在我的网站上切换语言的链接的背景图片。我的方法是检查标签内的语言代码,然后使用 jQuery 更改背景图像。
下面的代码将背景图像更改为条件语句中的第一个背景图像。但是当条件不满足,并且应该执行第二个语句时,它仍然执行第一个(或以某种方式执行失败)。控制台没有显示错误。
最后一个 li 元素由 PHP 脚本生成,可以根据 cmets 中的建议对其进行调整以包含 -data 属性。这将是一个很好的改进。目前它只是将语言代码作为列表项中的纯文本返回。
HTML
<nav id="top-menu">
<ul id="menu-top" class="nav et_disable_top_tier sf-js-enabled">
<li id="menu-item-263"><a href="/">Home</a></li>
<li id="menu-item-265"><a href="services">Services</a></li>
<li id="menu-item-412"><a href="/blog/">Blog</a></li>
<li><a href="/en/" style="background-image: url(https://www.example.nl/wp-content/themes/GH/images/flagUK.gif);">EN</a></li>
</ul>
</nav>
CSS
ul#menu-top > li:last-child > a {
text-indent: -9999px;
display: block;
height: 12px;
width: 18px;
background-repeat: no-repeat;
background-position: 50% 50%;
}
jQuery 代码:
$(document).ready(function(){
lang_flags_append();
function lang_flags_append() {
var $l = $( "ul#menu-top > li:last-child > a" ).text();
console.log($l);
$( "ul#menu-top li:last-child > a" ).css("background", "");
if ( $l = 'EN' ) {
$( "ul#menu-top > li:last-child > a" ).css("background-image", "url('https://www.example.nl/wp-content/themes/GH/images/flagUK.gif')");
} else if ($l = 'NL') {
$( "ul#menu-top > li:last-child > a" ).css("background-image", "url('https://www.example.nl/wp-content/themes/GH/images/flagNL.gif')");
}
}
});
【问题讨论】:
-
if ( $l === 'NL' ):你是在分配,而不是比较。这就是为什么总是执行第一个分支 -
一个锚元素不能包含另一个锚元素,您的选择器或 HTML 标记有问题。其余的,如我所见,请参阅@TrueBlueAussie 的 asnwser
-
添加了更新以涵盖我认为您想要的内容。请提供此类示例的 HTML 以避免混淆。您当前的代码被硬连接为仅处理第一个链接(从外观上看)。
标签: javascript jquery css