我正在尝试扩展这个但是在创建JS函数时我有点绿.我设法自己走了这么远,但唉......
当跨度获得任何值(在本例中为城市名称)时,我希望选择框自动匹配它.而且我想通过摆脱所有这些来扩展它,如果是的话.
$(document).ready(function() {
$('select#field1 option').removeAttr('selected');
var whereEvent = $('span#field2').html();
if (whereEvent == 'New York') {
$('select#field1 option[value=New York]').attr('selected', 'true');
} else if (whereEvent == 'Los Angeles') {
$('select#field1 option[value=Los Angeles]').attr('selected', 'true');
} else if (whereEvent == 'Tokyo') {
$('select#field1 option[value=Tokyo]').attr('selected', 'true');
} else if (whereEvent == 'London') {
$('select#field1 option[value=London]').attr('selected', 'true');
} else if (whereEvent == 'Sydney') {
$('select#field1 option[value=Sydney]').attr('selected', 'true');
} else if (whereEvent == 'Paris') {
$('select#field1 option[value=Paris]').attr('selected', 'true');
}
});
Run Code Online (Sandbox Code Playgroud)
有人可以帮帮我吗?我保证我会感激你的帮助.谢谢.
这是一个选项:
$(document).ready(function() {
$('select#field1 option').removeAttr('selected');
var whereEvent = $('span#field2').html();
var filter = 'select#field1 option[value=' + whereEvent + ']';
$(filter).attr('selected', 'true');
}
Run Code Online (Sandbox Code Playgroud)
或者你可以这样做:
$(document).ready(function() {
var filter = $('span#field2').html();
$('select#field1 option').each(function(){
this.selected = (this.value == filter);
});
}
Run Code Online (Sandbox Code Playgroud)