簡體   English   中英

獲取光譜顏色選擇器的父元素ID

[英]get parent element ID of a spectrum color picker

我在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中以$("#t1").spectrum發送輸入ID。

請幫我。 提前致謝。

您可以使用this ,但是這將捕獲輸入元素,因為插件已.basic.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);
     },                
});

也許這對您有用。

$("#h1").focus(function() {
    //code when div #h1 focused
});

$("#h2").focus(function() {
    //code when div #h2 focused
});

要么

this 

如Norlihazmey Ghazali所說,具有聚焦功能

感謝大家的幫助。

這是如何更改其父bgcolor:

change: function (color) 
{
   $(this).parent().parent().css('background',color);
},

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM