jquery - how to change the selector keeping the action same
Suppose I have an array Boxes={"#box5","#box3",#box1"","#box2","#box4"}
and I have a jquery statement
$(Boxes[2]).click(--------some code----------)
my problem is that the statement is always executed as - when box1 is clicked even though I swap the Box array several times in between. So even when Boxes[2] = "box2"
the code is still executed when I click box1 and not box2.
Is this so开发者_JS百科me sort of preprocessing?
When you call $(Boxes[2])
what matters is the value of Boxes[2]
on the time you call it.
So the better is hook the click event to all boxes and inside the code check whether the array value is the box being clicked or not.
Sample:
// bind to all elements that id begin with "box"
$("id^=[box]").click(function() {
// see if the clicked box is the one we want
if ($(this).id == Boxes[2]) {
// some code
}
})
精彩评论