JavaScript:IIF like 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8622580/
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
JavaScript: IIF like statement
提问by Alex Guerin
Coming from VB, JavaScript isn't very easy to get the hang of. Please don't be negative, I've tried and searched loads but with no luck. BTW, I'm creating a dropdown control initialized from a Select
option list in JS.
来自 VB,JavaScript 不是很容易掌握。请不要消极,我已经尝试并搜索了负载,但没有运气。顺便说一句,我正在创建一个从Select
JS 中的选项列表初始化的下拉控件。
Dummy code:
虚拟代码:
var col = 'tardis';
var x = '<option value="' + col + '">Very roomy</option>');
I would like to add selected
after the value of col ONLY if col is equal to 'screwdriver'.
selected
只有当 col 等于“螺丝刀”时,我才想在 col 的值之后添加。
I've tried using the IF statement with the ? and the : but can't seem to get my head around it. Having '' as the false value does not work. No items are selected and the list is blank. Remove the IF statement and all works.
我试过将 IF 语句与 ? 和 : 但似乎无法理解它。将 '' 作为假值不起作用。未选择任何项目且列表为空白。删除 IF 语句和所有工作。
Any ideas and again, sorry for the newb-ness.
任何想法,再次为新手感到抱歉。
回答by George Mauer
'<option value="' + col + '"'+ (col === "screwdriver" ? " selected " : "") +'>Very roomy</option>';
回答by jspcal
var x = '<option value="' + col + '"'
if (col == 'screwdriver') x += ' selected';
x += '>Very roomy</option>';
回答by Matt Ball
Something like this:
像这样的东西:
for (/* stuff */)
{
var x = '<option value="' + col + '" '
+ (col === 'screwdriver' ? 'selected' : '')
+ '>Very roomy</option>';
// snip...
}
回答by gilly3
If your end goal is to add elements to your page, just manipulate the DOM directly. Don't use string concatenation to try to create HTML - what a pain! See how much more straightforward it is to just create your element, instead of the HTML that represents your element:
如果您的最终目标是向页面添加元素,只需直接操作 DOM。不要使用字符串连接来尝试创建 HTML - 多么痛苦!看看创建您的元素而不是代表您的元素的 HTML 是多么简单:
var x = document.createElement("option");
x.value = col;
x.text = "Very roomy";
x.selected = col == "screwdriver";
Then, later when you put the element in your page, instead of setting the innerHTML
of the parent element, call appendChild()
:
然后,稍后当您将元素放入页面时,不要设置innerHTML
父元素的 ,而是调用appendChild()
:
mySelectElement.appendChild(x);
回答by Joe Phillips
I typed this in my URL bar:
我在 URL 栏中输入:
javascript:{ var col = 'screwdriver'; var x = '<option value="' + col + '"' + ((col == 'screwdriver') ? ' selected' : '') + '>Very roomy</option>'; alert(x); }