gpt4 book ai didi

javascript - 循环数据属性并设置对应的输入值

转载 作者:行者123 更新时间:2023-12-03 07:24:46 26 4
gpt4 key购买 nike

$(document).on('click', '.atitle', function(){
//for each data attr - corresponding input value = data.value
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='atitle' data-x='lorem' data-y='ipsum' data-z='dolor'>title</div>
<br>
<input type='text' id='input_x'>
<input type='text' id='input_y'>
<input type='text' id='input_z'>

结果:
input_x 具有值 lorem
input_y 具有值 ipsum
input_z 的值为 dolor

最佳答案

$(document).on('click', '.atitle', function() {
// get data of all data attributes
// (it's an object like this { x: "lorem", y: "ipsum", ...)}
let data = $(this).data();
// Set data to input values.
Object.entries(data).forEach(([key, value]) => {
let elem = $(`#input_${key}`);
// Check if elem exists before trying to assign a value.
// Just in case if .atitle contains some data attributes,
// which have no mapping to an input element.
elem && elem.val(value);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='atitle' data-x='lorem' data-y='ipsum' data-z='dolor'>title</div>
<br>
<input type='text' id='input_x'>
<input type='text' id='input_y'>
<input type='text' id='input_z'>

关于javascript - 循环数据属性并设置对应的输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62366392/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com