点击时切换div中的字符

时间:2014-06-18 20:37:04

标签: javascript jquery html

我希望以下代码在点击.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'>
        &#8595;
    </div>
</div>

但它没有做任何事情。另一方面,如果我将if...else if取出,只需将字符设置为$(this).children('.articleArrow').html('&#8593;');即可。因此设置角色的工作原理是if...else,如果没有被正确触发,我就无法找出原因。

You can view it live on my website here(不要兴奋,这不是实际的管理面板!)

2 个答案:

答案 0 :(得分:2)

如果我使用unicode字符进行比较,则适合我:

$(".articleTitle").click(function () {
    if ($(this).children('.articleArrow').html() == '↓') $(this).children('.articleArrow').html('&#8593;');
    else if ($(this).children('.articleArrow').html() == '↑') $(this).children('.articleArrow').html('&#8595;');
});

<强> jsFiddle example

答案 1 :(得分:1)

只需使用.slideTogglecomplete 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') ? '&#8593;' : '&#8595;' );
        //  inside the .html statement is a simple `inline if` statement that simply says:
        //      if true ? do this : else do this
    });
});

Example

Behind the show


普通代码:

$(".articleTitle").click(function () {
    var a = $(this).find(".articleArrow");
    $(this).siblings(".articleContent").slideToggle("slow", function () {
        a.html($(this).is(":visible") ? "&#8593;" : "&#8595;")
    })
});