get ID of this
I've written my own jQuery clicking function, but for an unkown reason, it doesn't work. I get error on line 4.
for (var i = 1;i<=3;i++){
$("#Block"+i).click(function(){
$(this).effect("shake", function(){
if (this == "#Block3"){
window.open('contact.html','blank');//open link link in a new page
}
});
});
}
Could you please help me?
Explanation
this
on line 4 returns (or is) an object, it is a DOM element (such as <div>
or something like that) You can't compare object this
and string "#Block3"
.
These two things are very different. It is like comparing pears and apples.
Take a look at JavaScript Data Types I think, it could help you.
Documentation
See the documentation of this object.
Getting ID of an element How can I get the ID of an element using jQuery?
Edit of your code
You have to get the ID of the object (this) and then compare it with the string "Block3"
for (var i = 1; i <= 3; i++) {
$("#Block" + i).click(function() {
$(this).effect("shake", function() {
if (this.id == "Block3") {
window.open('contact.html', 'blank'); //open link link in a new page
}
});
});
}
Edit of your code 2
jQuery is here to help you to do less of code. Take a while to look at some tutorials.
Your code could be shortened to something like this
$('.blocks-container').on('click', '.block', function() {
$(this).effect('shake', function() {
if (this.id == 'Block3')
window.open('contact.html', 'blank'); //open link link in a new page
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="blocks-container">
<div id="Block1" class="block">Block1</div>
<div id="Block2" class="block">Block2</div>
<div id="Block3" class="block">Block3</div>
<div id="Block4" class="block">Block4</div>
<div id="Block5" class="block">Block5</div>
</div>
this
in your code is a DOMElement. When coerced to a string it will never match #Block3
, hence your if
condition never hits.
Assuming you're trying to match the id
of a specific element, then you just need to compare against the id
property of this
:
(var i = 1; i <= 3; i++){
$("#Block" + i).click(function(){
$(this).effect("shake", function(){
if (this.id === "Block3") {
window.open('contact.html', 'blank');
}
});
});
}
Also note that it would be much better practice to put a common class on all the #BlockX
elements and use a single event handler on all of them:
$('.block').click(function() {
$(this).effect("shake", function(){
if (this.id === 'Block3')
alert('you clicked block3!');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<div id="Block1" class="block">Block1</div>
<div id="Block2" class="block">Block2</div>
<div id="Block3" class="block">Block3</div>
<div id="Block4" class="block">Block4</div>
<div id="Block5" class="block">Block5</div>
链接地址: http://www.djcxy.com/p/83314.html
上一篇: 获取表格ID
下一篇: 得到这个ID