Javascript jQuery 函数中的“If”-“else”语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2489189/
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
'If'-'else' statement within jQuery function
提问by Vonder
I have the following code in JavaScript and jQuery:
我在 JavaScript 和 jQuery 中有以下代码:
$("<li />")
.html('Some HTML')
I would like to be able to change the content of .html by using an if-elsestatement. My code should be something like this, however it's not working.
我希望能够使用if-else语句更改 .html 的内容。我的代码应该是这样的,但是它不起作用。
var showinfo = <?php echo '$action'; ?>
$("<li />")
if (showinfo == 'action1'){
.html('Some HTML')
else {
.html('Other HTML')
}
How should I change it?
我应该怎么改?
回答by Tobias Cohen
Ternary operator?
三元运算符?
$("<li />").html((showinfo == 'action1') ? 'Somehtml' : 'Other html');
The important thing to understand is that your first bit of code is being interpreted as one statement, not two:
要理解的重要一点是,您的第一段代码被解释为一个语句,而不是两个:
$("<li />")
.html('Somehtml')
//Is the same as:
$("<li />").html('Somehtml');
You're getting mixed up because you're not using semicolons to terminate your statements. JavaScript allows this to support legacy code, but if you're writing code now you really should be using them.
您会混淆,因为您没有使用分号来终止您的语句。JavaScript 允许它支持遗留代码,但如果你现在正在编写代码,你真的应该使用它们。
回答by Adam Hopkinson
Don't interrupt the jquery chaining:
不要中断 jquery 链接:
var showinfo = '<?php echo $action; ?>'
if (showinfo == 'action1'){
$("<li />").html('Somehtml')
} else {
$("<li />").html('Other html')
}
Note: I also corrected an error in your php echostatement and a missing bracket in your if...else
注意:我还更正了您的 phpecho语句中的错误和您的if...else
回答by Ali Habibzadeh
var listItem = $("#yourLi");
if (showinfo == 'action1'){
listItem.html('Somehtml')
else {
listItem.html('Other html')
}
回答by ChrisP
You can shorten it as follows:
您可以按如下方式缩短它:
var showinfo = '<?php echo '$action'; ?>'
$("<li />")
.html( (showinfo == 'action1' ? 'Somehtml' : 'Other html') );
.html can be on the same line or a separate line as the statement is terminated with a semicolon. If you have multiple methods on a single selector I find separating them on multiple lines more readable.
.html 可以在同一行或单独的行中,因为语句以分号结尾。如果您在单个选择器上有多个方法,我发现将它们分开在多行上更具可读性。
回答by thomasrutter
Adam's answeris pretty spot-on. To save a little bit of unnecessary duplication however you could modify it slightly to this:
亚当的回答非常准确。为了节省一点不必要的重复,你可以稍微修改一下:
var
showinfo = '<?php echo $action; ?>',
listitems = $("<li />");
if (showinfo == 'action1') {
listitems.html('Somehtml');
} else {
listitems.html('Other html');
}

