我希望以下代码在点击.articleArrow
时在向上和向下箭头之间切换.articleTitle
的html内容:
的jQuery
$(".articleTitle").click(function () {
if ($(this).children('.articleArrow').html() == '↑')
$(this).children('.articleArrow').html('↓');
else if ($(this).children('.articleArrow').html() == '↓')
$(this).children('.articleArrow').html('↑');
});
HTML
<div class='articleTitle'>
Blah
<div class='articleArrow'>
↓
</div>
</div>
但它没有做任何事情。另一方面,如果我将if...else if
取出,只需将字符设置为$(this).children('.articleArrow').html('↑');
即可。因此设置角色的工作原理是if...else
,如果没有被正确触发,我就无法找出原因。
You can view it live on my website here(不要兴奋,这不是实际的管理面板!)
答案 0 :(得分:2)
如果我使用unicode字符进行比较,则适合我:
$(".articleTitle").click(function () {
if ($(this).children('.articleArrow').html() == '↓') $(this).children('.articleArrow').html('↑');
else if ($(this).children('.articleArrow').html() == '↑') $(this).children('.articleArrow').html('↓');
});
<强> jsFiddle example 强>
答案 1 :(得分:1)
只需使用.slideToggle
的complete callback method和{jQuery的:visible
选择器,您就可以轻松完成此操作而不会出现凌乱的if statement
。
$(".articleTitle").click(function () {
// 1st, i go ahead and asign our arrow element to a variable for use in callback
var arrow = $(this).find('.articleArrow');
$(this).siblings('.articleContent').slideToggle("slow", function(){
// this is the `complete` callback method
// in here, we can now manipulate whatever we need to when the "toggle" is `complete`
arrow.html( $(this).is(':visible') ? '↑' : '↓' );
// inside the .html statement is a simple `inline if` statement that simply says:
// if true ? do this : else do this
});
});
show
普通代码:
$(".articleTitle").click(function () {
var a = $(this).find(".articleArrow");
$(this).siblings(".articleContent").slideToggle("slow", function () {
a.html($(this).is(":visible") ? "↑" : "↓")
})
});