[英]How to synchronize data-attr and select box vaule?
I have two elements like: 我有两个要素,例如:
<select id="data">
<option value=1>hoge</option>
<option value=2>fuga</option>
<option value=3>hogehoge</option>
</select>
<a href="#1" data-id="1">hoge</a>
<a href="#2" data-id="2">fuga</a>
<a href="#3" data-id="3">hogehoge</a>
if I pick hoge on select box, I want data-id="1" to be selected and do some stuff (changing background etc.) using jQuery. 如果我在选择框上选择hoge,则希望选择data-id =“ 1”并使用jQuery做一些事情(更改背景等)。 If I click
a[data-id="3"]
, select box option 'hogehoge' to be selected vice versa. 如果单击
a[data-id="3"]
,则选择框选项“ hogehoge”,反之亦然。
any help would be appreciated. 任何帮助,将不胜感激。
Have a look at the last line in the click listener. 查看点击侦听器的最后一行。 You can trigger a change on an element which will call the corresponding listener instead of duplicating code.
您可以在元素上触发更改,该更改将调用相应的侦听器,而不是复制代码。
$(function() { $("#data").on("change", function() { $("a").removeClass("active"); // remove active class from all <a> $("a[data-id='" + $(this).val() + "']").addClass("active"); // add active class to link with corresponding data-id }); $("a").on("click", function() { $("#data option[value='" + $(this).data("id") + "']").prop("selected", true); // change the selected value $("#data").trigger("change"); // trigger change on #data to keep active link synced }); });
.active { background-color: cornflowerblue; color: white; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="data"> <option value=1>hoge</option> <option value=2>fuga</option> <option value=3>hogehoge</option> </select> <a href="#1" data-id="1" class="active">hoge</a> <a href="#2" data-id="2">fuga</a> <a href="#3" data-id="3">hogehoge</a>
$(document).ready( function(){
$('a').click(function(){
var id = $(this).data('id');
$('#data').find('option[value='+id+']').prop('selected',true);
)};
)};
I implemented the function in JSFiddle https://jsfiddle.net/dphf267u/ 我在JSFiddle https://jsfiddle.net/dphf267u/中实现了该功能
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.