Try
$('a.fruit').click(function (e) {
e.preventDefault();
var selected = this.className.match(/apple-[^\s$]+/)[0];
$('#fruits option[value*="' + selected + '"]').prop('selected', true);
});
Demo: Fiddle
سؤال
When I click a link I'd like the dropdown to change to match the link I've clicked. I could write an if-statement with hasClass, but I would like to make it short. Links can contain multiple classes - I only want to match on the apple-x class. This is what I've got:
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;
});
المحلول
Try
$('a.fruit').click(function (e) {
e.preventDefault();
var selected = this.className.match(/apple-[^\s$]+/)[0];
$('#fruits option[value*="' + selected + '"]').prop('selected', true);
});
Demo: Fiddle