【问题标题】:get parent element ID of a spectrum color picker获取光谱颜色选择器的父元素 ID
【发布时间】:2017-06-17 17:34:39
【问题描述】:

我在 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).parent() 获取您选择的颜色选择器 div。
  • 谢谢。 this 关键字是解决方案。

标签: javascript jquery color-picker spectrumjs


【解决方案1】:

您可以使用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);
     },                
});

【讨论】:

    【解决方案2】:

    也许这对你有用。

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

    this 
    

    Norlihazmey Ghazali 所说的具有焦点功能

    【讨论】:

      【解决方案3】:

      感谢大家的帮助。

      这是更改其父 bgcolor 的方法:

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

      【讨论】:

        猜你喜欢
        • 2013-10-19
        • 2013-08-13
        • 2013-04-23
        • 2016-05-08
        • 2013-04-26
        • 1970-01-01
        • 1970-01-01
        • 2011-12-07
        • 1970-01-01
        相关资源
        最近更新 更多