0

I'm trying to get my jquery to select a different element based on a value stored in the clicked elements attribues. But it keeps animating the clicked element. Because there are multiple classes named element1 I figured this would be the easiest way to animate a specified div associated with that button.

$(".element1").click(function(){
    var expander = $(this).attr("id");
    var expander2 = '#' + expander;
    test(expander2);


});

function test(expander3) {
    if (toggle == true) {
        $(expander3).animate({height:200}, {queue:false}, "slow");
        $(expander3).animate({width:400}, {queue:false}, "slow");
        toggle = false;
    } else if (toggle == false) {
        $(expander3).animate({height:0}, {queue:false}, "slow");
        $(expander3).animate({width:50}, {queue:false}, "slow");
        toggle = true;
    }
}

I did alert(expander2) and I'm getting the correct id (i.e. #id1, #id2 etc etc) but it is only animating the .element1, .element2 etc etc. It's like it's ignoring the correct id.

Here's how the html looks if that helps:

<input type="button" id="id1" class="element1" value="TextGoesHere"></input>

<div id="id1">
    This should be animating.
</div>
4

1 回答 1

2

您的 html 无效:该id属性应该是唯一的。当您尝试使用它进行选择时id$("#idThatIsNotUnique")它只会找到第一个元素(或者在某些浏览器中可能是最后一个元素)id- 在您的情况下是输入,而不是 div。

您可以改用 html5data-属性:

  <input type="button" data-animate-id="id1" class="element1" value="TextGoesHere"></input>

  <div id="id1">This should be animating.</div>

然后是JS:

        $(".element1").click(function(){
            var expander = $(this).attr("data-animate-id");
            var expander2 = '#' + expander;
            test(expander2);
        });
于 2013-06-02T03:14:43.493 回答