jQuery 单击函数内的jQuery if语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13066469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery if statement inside click function
提问by Alessandro
I have a click event inside of which I would like to load different divs according to what has been clicked:
我有一个点击事件,我想根据点击的内容在其中加载不同的 div:
var open = $('.open');
open.click(function(evt) {
evt.preventDefault();
overlay.fadeIn(400, function(){
box.fadeIn(500);
// if something load box2
// if something load box3
});
Open is a class given to the links which relate to box, box2 and box3. How can I load the content for box2, would I have to use a specific class for each of them?
Open 是给与 box、box2 和 box3 相关的链接的类。如何加载 box2 的内容,是否必须为每个内容使用特定的类?
回答by Divick
Open is a class given to the links which relate to box, box2 and box3. How can I load the >content for box2, would I have to use a specific class for each of them?
Open 是给与 box、box2 和 box3 相关的链接的类。如何加载 box2 的 >content,我是否必须为它们中的每一个使用特定的类?
No, you can simply write your code with if statement:
不,您可以简单地使用 if 语句编写代码:
var open = $('.open');
open.click(function(evt) {
evt.preventDefault();
overlay.fadeIn(400, function(){
box.fadeIn(500);
if (cond1){ load box2 }
else if (cond2) {load box3 }
});
回答by Nikko Reyes
Try this:
尝试这个:
var open = $('.open');
open.click(function(evt) {
evt.preventDefault();
box= $(this).attr('rel');//get the rel of your clicked link.
overlay.fadeIn(400, function(){
$('#'+box).fadeIn(500);//fadein the div your link relates to if it is your div's id.
});
回答by bool.dev
Edit:After looking at the fiddle, you'll have to give each clickable <p>
an id, and load the corresponding box.
编辑:查看小提琴后,您必须给每个可点击<p>
的 id,并加载相应的框。
Html:
网址:
<p class="terms open" id="box1_clicker">I agree to the <a href="">terms and conditions.</a></p>
Js:
JS:
if($(this).attr("id")=="box1_clicker") {
// do something
}
You could specify an id for each of the boxes, and then check inside the click which box's link was clicked, using jquery's parent()
:
您可以为每个框指定一个 id,然后使用jquery 来parent()
检查点击了哪个框的链接:
if($(this).parent().attr("id") == "box1") {
//some code
}
else if ($(this).parent().attr("id") == "box2") {
//some code
}
// so on