我在 2 个不同的 div 中有 2 个颜色选择器。
<div class="panel-heading" style="width:100%" id="h1">
<span style="float:right; padding-right:10px;" class="close"> <input type='text' class="basic" id="t1"/> </span>
</div>
<div class="panel-heading" style="width:100%" id="h2">
<span style="float:right; padding-right:10px;" class="close"> <input type='text' class="basic" id="t2"/> </span>
</div>
这是我的频谱图选择器 JS:
$(document).ready(function () {
$(".basic").spectrum({
color: "rgb(244, 204, 204)",
showPaletteOnly: true,
hideAfterPaletteSelect: true,
change: function (color)
{
setBackgroundColor(color);
},
palette: [
["rgba(168, 255, 102, 0.29)", "rgb(67, 67, 67)", "rgb(102, 102, 102)",
"rgb(204, 204, 204)", "rgb(217, 217, 217)", "rgb(255, 255, 255)"],
["rgb(152, 0, 0)", "rgb(255, 0, 0)", "rgb(255, 153, 0)", "rgb(255, 255, 0)", "rgb(0, 255, 0)",
"rgb(0, 255, 255)", "rgb(74, 134, 232)", "rgb(0, 0, 255)", "rgb(153, 0, 255)", "rgb(255, 0, 255)"]
]
});
});
现在在 setBackgroundColor() 函数中我如何知道我选择了哪个颜色选择器 div。(我正在尝试更改 div 的背景颜色) 即 H1 或 H2。
注意:我不想在 jquery 中将输入 ID 发送为 $("#t1").spectrum
。
请帮助我。提前致谢。
最佳答案
您可以使用this
,但这将捕获输入元素,因为插件附加到.basic
元素。要获取父级本身,只需使用 .parent()
或 .closest()
:
$(".basic").spectrum({
color: "rgb(244, 204, 204)",
showPaletteOnly: true,
hideAfterPaletteSelect: true,
change: function (color) {
// use this
console.log(this); // will show <input type='text' class="basic" id="t1"/>
// to access parent element use .closest
console.log( $(this).closest('.panel-heading') );
// or
console.log( $(this).closest('.close') );
setBackgroundColor(color);
},
});
关于javascript - 获取光谱颜色选择器的父元素 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41971857/