[英]Code is selecting wrong element to animate
I'm trying to get my jquery to select a different element based on a value stored in the clicked elements attribues. 我正在尝试让我的jquery根据存储在点击元素属性中的值来选择不同的元素。 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的类,我认为这是设置与该按钮关联的指定div的最简单方法。
$(".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 (ie #id1, #id2 etc etc) but it is only animating the .element1, .element2 etc etc. It's like it's ignoring the correct id. 我做了警告(expandder2),我得到了正确的id(即#id1,#id2等等),但它只是动画.element1,.element2等等。这就像它忽略了正确的id。
Here's how the html looks if that helps: 这是html看起来如何有用:
<input type="button" id="id1" class="element1" value="TextGoesHere"></input>
<div id="id1">
This should be animating.
</div>
Your html is invalid: the id
attribute should be unique. 您的html无效:
id
属性应该是唯一的。 When you try to select by id
with $("#idThatIsNotUnique")
it will just find the first element (or potentially the last element in some browsers) with that id
- in your case the input, not the div. 当您尝试使用
$("#idThatIsNotUnique")
通过id
进行选择时,它将只找到具有该id
的第一个元素(或者可能是某些浏览器中的最后一个元素) - 在您的情况下是输入,而不是div。
You could use an html5 data-
attribute instead: 您可以使用html5
data-
属性:
<input type="button" data-animate-id="id1" class="element1" value="TextGoesHere"></input>
<div id="id1">This should be animating.</div>
And then JS: 然后是JS:
$(".element1").click(function(){
var expander = $(this).attr("data-animate-id");
var expander2 = '#' + expander;
test(expander2);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.