jQuery show/hide 选项(如果选择了按钮)

jQuery show/hide options if button selected

如何将 SELECT 表格从。

我有这个代码:

var $clonedOpts = $("#layout_select").children().clone();

$("#column_select").change(function() { 
  var $layOpts = $clonedOpts.clone().filter('[value^=' + $(this).val() + ']');
  $("#layout_select").html($layOpts);
}).change();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="column_select" id="column_select">
  <option value="col1">1 column</option>
  <option value="col2">2 column</option>
  <option value="col3">3 column</option>
</select>

<select name="layout_select" id="layout_select">
  <!--Below shows when '1 column' is selected is hidden otherwise-->
  <option value="col1">none</option>

  <!--Below shows when '2 column' is selected is hidden otherwise-->
  <option value="col2_ms">layout 1</option>
  <option value="col2_sm">layout 2</option>

  <!--Below shows when '3 column' is selected is hidden otherwise-->
  <option value="col3_mss">layout 3</option>
  <option value="col3_ssm" selected="selected">layout 4</option>
  <option value="col3_sms">layout 5</option>
</select>

我想更改此代码(select 选项):

<select name="column_select" id="column_select">
  <option value="col1">1 column</option>
  <option value="col2">2 column</option>
  <option value="col3">3 column</option>
</select>

到此代码(TAB 形式):

<div class="tab">
  <button>TAB1</button>
  <button>TAB2</button>
  <button>TAB3</button>
</div>

我应该在 javascript 中更改什么?

您可以使用 data- 属性在按钮上附加值

并将事件更改为 click

var $clonedOpts = $("#layout_select").children().clone();

$(".tab button").click(function() { 
  var $layOpts = $clonedOpts.clone().filter('[value^=' + $(this).data("val") + ']');
  $("#layout_select").html($layOpts);
});
$(".tab button").eq(0).click();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tab">
  <button data-val="col1">TAB1</button>
  <button data-val="col2">TAB2</button>
  <button data-val="col3">TAB3</button>
</div>

<select name="layout_select" id="layout_select">
  <!--Below shows when '1 column' is selected is hidden otherwise-->
  <option value="col1">none</option>

  <!--Below shows when '2 column' is selected is hidden otherwise-->
  <option value="col2_ms">layout 1</option>
  <option value="col2_sm">layout 2</option>

  <!--Below shows when '3 column' is selected is hidden otherwise-->
  <option value="col3_mss">layout 3</option>
  <option value="col3_ssm" selected="selected">layout 4</option>
  <option value="col3_sms">layout 5</option>
</select>