使用 jQuery 在 select 菜单中移动 selected 属性

Move the selected attribute in a select menu using jQuery

我有三个产品页面。让我们将它们识别为 Hot Chocolate、Mocha Coffee、Espresso

每个页面底部都有一个表单,具有相同的select菜单:

<form>
    <select class="ProductType">
        <option selected>(Please choose)</option>
        <option>Hot Chocolate</option>
        <option>Mocha Coffee</option> 
        <option>Espresso</option>
    </select>
</form>

周围还有一个 div,它包含一个唯一的 class 值,用于标识 page/product。例如:

<div class="hot-chocolate"> ... </div>

我可以在 div 之外编辑它,但我不能手动更改 form 标签内的任何内容。

是否可以使用 jQuery 将 selected 属性动态移动到与当前正在查看的页面相匹配的 option(即以某种方式与 class 周围的名称 div, 即使选项值是带空格的短语)?

以下假设您要 select 值为 "Hot Chocolate" 的选项。请注意 class 名称区分大小写(必须与选项值的大小写匹配)

Html(注意 id 属性添加到 <div>

<div id="selection" class="Hot-Chocolate"> ... </div>
....
<form>
  <select class="ProductType">
    <option selected>(Please choose)</option>
    <option>Hot Chocolate</option>
    <option>Mocha Coffee</option> 
    <option>Espresso</option>
  </select>
</form>

脚本

var selection = $('#selection').attr('class').replace('-', ' ');
$('.ProductType').val(selection);

参考Fiddle