我正在尝试使用jQuery基于单选按钮选择更改一些文本,但我似乎无法让它工作。这是我的代码:
HTML
<input type="radio" name="finish_id" id="1" value="1" checked />
<label for="1" id="veteran"></label>
<input type="radio" name="finish_id" id="2" value="2" />
<label for="2" id="elite"></label>
<input type="radio" name="finish_id" id="3" value="3" />
<label for="3" id="legendary"></label>
<span id="finish_name"></span>
JS
// Set variables
var finish[] = "something";
var finish[] = "something else";
var finish[] = "another thing";
// Change finish name based on radio selection
$(document).ready(function() {
$("input[name='finish_id']").change(function() {
$('#finish_name').text( finish[$(this).val()] );
}).change();
});
关于数组编号为$(this).val()
,我可能不在了,我不知道你是否可以选择那种方式,但即使我把它设置为$('#finish_name').text( finish[1] );
我也得到unexpected token [
1}}错误。如何使用.text()的数组值?
答案 0 :(得分:3)
这不是你如何在javascript中声明一个数组
尝试
var finish = ["something",
"something else",
"another thing"];
// Change finish name based on radio selection
$(document).ready(function() {
$("input[name='finish_id']").change(function() {
$('#finish_name').text( finish[$(this).val()] );
}).change();
});
或者使其更具可扩展性/ html5-esque ....
<input type="radio" name="finish_id" value="1" data-message='something' onchange="javasript:$('#finish_name').text( finish[$(this).val()] )">
<input type="radio" name="finish_id" value="2" data-message='something else' onchange="javasript:$('#finish_name').text( finish[$(this).val()] )">
<input type="radio" name="finish_id" value="3" data-message='another thing' onchange="javasript:$('#finish_name').text( finish[$(this).val()] )">
<span id="finish_name"></span>
答案 1 :(得分:1)
你有几个问题:
finish
的变量。在MDN's article上阅读有关数组的更多信息。您手动触发更改事件的方式是导致事件触发最后一个单选按钮。您可以使用.first
方法选择第一个单选按钮,并在该元素上触发仅的更改事件。
// Set variables
var finish = ['something', 'something else', 'another thing'];
// Change finish name based on radio selection
$(document).ready(function () {
$("input[name='finish_id']").change(function () {
$('#finish_name').text(finish[$(this).val()-1]);
}).filter(":checked").change();
});