当我点击链接时,我希望下拉列表更改为与我点击的链接相匹配。我可以用 hasClass 写一个if语句,但我想简短一点。链接可以包含多个类 - 我只想匹配 apple-x 类。这就是我所拥有的:
HTML
<a href="#" class="apple-1 fruit">Apple 1</a>
<a href="#" class="fruit apple-2 tasty">Apple 2</a>
<a href="#" class="apple-3 fruit no-so-tasty">Apple 3</a>
<select id="fruits">
<option value="apple-1 fruit">Apple 1</option>
<option value="apple-2 fruit">Apple 2</option>
<option value="apple-3 fruit">Apple 3</option>
</select>
的jQuery
$('a.fruit').click(function () {
var selected = "what goes here?";
$('#fruits option[value*="'+selected+'"]').attr('selected','selected');
return false;
});
答案 0 :(得分:2)
尝试
$('a.fruit').click(function (e) {
e.preventDefault();
var selected = this.className.match(/apple-[^\s$]+/)[0];
$('#fruits option[value*="' + selected + '"]').prop('selected', true);
});
演示:Fiddle