使用 JS(jQuery 也可以)...
有没有办法使用 switch 语句来更改变量内的变量?
相反...如何设置 case 语句中定义的变量来覆盖所使用的
**REPLACE-THIS**作为脚本顶部的占位符变量。
请参阅此 fiddle 的用法:DEMO
我宁愿在代码输出中显示一个数字(由“count”定义),而不是像此时那样默认的**REPLACE-THIS**。
例如...
HTML
<div id="phase1" class="phase1">
<h1>Foo | Bar test</h1>
<form name="phase1" >
<ul style="list-style:none;">
<li>Slot 1: <select name="slot1">
<option value="foo">Foo</option>
<option value="bar">Bar</option>
</select></li>
<li>Slot 2: <select name="slot2">
<option value="foo">Foo</option>
<option value="bar">Bar</option>
</select></li>
</ul>
<br />
<input type="button" value="Build" onclick="Build();">
</form>
</div>
<span id="data"></span>
JS
var count= '**REPLACE-THIS**';
var uniqueID= '<div class="example" id="FooBarDiv'+count+'">';
switch (document.phase1.slot1.value){
case 'foo':
slotOne = "Foo1 is:<br>";
count= '1';
slotOne += uniqueID;
break;
case 'bar':
slotOne = "Bar1 is:<br>";
count= '1';
slotOne += uniqueID;
break;
}
switch (document.phase1.slot2.value){
case 'foo':
slotTwo = "Foo2 is:<br>";
count= '2';
slotTwo += uniqueID;
break;
case 'bar':
slotTwo = "Bar2 is:<br>";
count= '2';
slotTwo += uniqueID;
break;
}
output = slotOne+slotTwo;
document.getElementById("data").innerHTML=output;
请注意,这是一个非常淡化的示例。该工作示例将根据下拉列表中的选择,将一个大型 HTML block 放置到具有唯一标签 ID 的页面上。
稍后将通过 getElementbyID
脚本定位这些 ID,因此,如果使用“FOO”两次,脚本仍将按预期运行并根据需要调用“FooBarDiv1”和“FooBarDiv2”。
最佳答案
简单的替换就足够了。
slotOne = slotOne.replace('**REPLACE-THIS**',count);
重复其余部分。 尽管您应该考虑创建您正在使用的元素的数组。
如你所愿:)
这使用 jquery。
function Build() {
var output = "<br>",count= '**REPLACE-THIS**';
$("#phase1").find("select").each(function(index) {
output += switcharoo($(this).val(), index + 1) + "<br>";
});
document.getElementById("data").innerHTML=output;
}
function switcharoo(value, count) {
var uniqueID= '<div class="example" id="FooBarDiv'+count+'">';
var slot = "";
switch (value){
case 'foo':
slot = "Foo";
break;
case 'bar':
slot = "Bar";
break;
}
slot += count + " is:<br>" + uniqueID;
return slot.replace('**REPLACE-THIS**',count);
}
Update using jquery with each method 请注意,它还可以进一步优化。但这应该让你思考一下。 switcharoo 可以重写为仅切换为仅给出“foo”或“bar”,然后也可以将其放置在您的 return 语句中。
关于javascript - 更改 case 语句中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23434092/