简体   繁体   English

如何将ID设为变量并在函数中使用

[英]How to make ID as variable and use it in function

I have this code. 我有这个代码。 It's actually a test. 这实际上是一个测试。 I want to use the variable hoveredColor to create a function changing the "this" div's background. 我想使用变量hoveredColor创建一个函数来更改“ this” div的背景。 But i can't seem to make it work. 但我似乎无法使其正常工作。

<script>
$(document).ready(function(){
  var currentcolor = "red";
  var hovercolor="";
  var hoveredColor = "";
  setColor();
  $("#settings div").hover(function(){
    hoveredColor = $(this).attr('id');
  }); 

  $("#black").hover(function(){
    hovercolor = $("#black").attr("id");
    document.getElementById('this').style.backgroundColor=hovercolor;
  },function(){
    document.getElementById('this').style.backgroundColor=currentcolor;
  });
  $("#"+hoveredColor).click(function(){ 
    currentcolor = $("#"+hoveredColor).attr('id');
    setColor();
  });

</script>

<div style="display: none;width:100%;" id="settings">
    <div style="width: 50px;height:50px; background-color: blue; float: left;display: block;margin-left: 10px" id="blue"> ff </div>
    <div style="width: 50px;height:50px; background-color: black; float: left;display: block;margin-left: 10px" id="black"> Black </div>
    <div style="width: 50px;height:50px; background-color: pink; float: left;display: block;margin-left: 10px" id="pink"> Pink </div>
</div>


<div style="width: 100%; height: 100px;margin-top: 75px;" id="this">
    <p>I hope this works.</p>
</div>

I have improved your script a little, and here is what I have done: 我对您的脚本进行了一些改进,这是我所做的:

  1. Declare a global colour called currentcolor , as your code has shown, so that the #this div reverts to red background when the mouse leaves the child <div> in #settings . 如代码所示,声明一个称为currentcolor的全局颜色,以便当鼠标离开#settings的子#settings <div>#settings #this div恢复为红色背景。
  2. Declare a global variable called fixcolor . 声明一个名为fixcolor的全局变量。 This will let us know if the user has clicked on a div to set/fix the color, which we will update it later so that this does not interfere with the mouse leave event. 这将让我们知道用户是否单击了div来设置/固定颜色,稍后我们将对其进行更新,以免干扰鼠标离开事件。

Distilling all that information above, here is the jQuery code (and view the demo fiddle here ): 提取上面的所有信息,这是jQuery代码(并在此处查看演示小提琴 ):

$(function() {
    // Define global variables
    var currentcolor = 'red',
        fixcolor = false;

    $('#settings div').hover(function() {
        // Mouseover
        $('#this').css('background-color', $(this).attr('id'));
    }, function() {
        // Mouseout
        if(!fixcolor) $('#this').css('background-color', currentcolor);
    }).click(function() {
        // Bind click
        $('#this').css('background-color', $(this).attr('id'));
        fixcolor = true;
    });
});

However, here are some suggestions: 但是,这里有一些建议:

  1. Store the colour not in the ID, but as a HTML5 data- attribute . 颜色不存储在ID中,而是存储为HTML5 data-属性 This allows you to change the color of the divs without needing to update the ID and its selectors in your stylesheet, if any. 这使您可以更改div的颜色,而无需更新样式表中的ID及其选择器(如果有)。
  2. Unhide the #settings . 取消隐藏#settings I don't see a point in hiding, as it simply renders the script unusable since all the divs are hidden from the user, anyway. 我看不到隐藏的意义,因为它会使脚本无法使用,因为无论如何所有div都对用户隐藏了。

To use the data- attribute, replace id with a name of your choice, say data-bgcolor : 要使用data-属性,请将id替换为您选择的名称,例如data-bgcolor

<div style="width:100%;" id="settings">
    <div style="..." data-bgcolor="blue"> ff </div>
    <!-- MORE -->
</div>

And the value in this attribute can be accessed by either using $(this).data('bgcolor') or $(this).attr('data-bgcolor') . 并且可以使用$(this).data('bgcolor')$(this).attr('data-bgcolor')访问此属性中的值。

Since your JavaScript code so tightly depends on the format of your HTML markup, it might be a good idea to handle creating that HTML inside of your JavaScript. 由于您的JavaScript代码非常紧密地取决于HTML标记的格式,因此最好在JavaScript中创建HTML。 If you need to make changes to this little 'component' of your page, you can do it in one location (the .js) instead of having to make changes in your HTML and JavaScript. 如果您需要对页面的这个小“组件”进行更改,则可以在一个位置(.js)中进行更改,而不必在HTML和JavaScript中进行更改。

Here's what the might look like. 这就是可能的样子。

 var DEFAULT_COLOR = 'red', COLOR_OPTIONS = [ { 'text': 'Blue', 'color': 'blue' }, { 'text': 'Black', 'color': 'black' }, { 'text': 'Pink', 'color': 'pink' }, ], COLOR_OPTION_TEMPLATE = '<div class="color-option" data-color="{{color}}" style="background-color: {{color}};">{{text}}</div>', settings_div = $('#settings'), bg_change_div = $('#this'), color_options_html = '', color_option_html = ''; function setBgColor(ele, color) { $(ele).css('background-color', color); } // Build HTML for the color-options divs. $.each(COLOR_OPTIONS, function(i, color_option) { color_option_html = COLOR_OPTION_TEMPLATE.replace(/{{color}}/g, color_option.color); color_option_html = color_option_html.replace(/{{text}}/, color_option.text); color_options_html += color_option_html; }); $(document).ready(function() { // add color-options HTML to #settings settings_div.html(color_options_html); // set default background-color for #this setBgColor(bg_change_div, DEFAULT_COLOR); settings_div.on('mouseenter', '.color-option', function(e) { setBgColor(bg_change_div, $(e.currentTarget).data('color')); }); settings_div.on('mouseleave', '.color-option', function() { setBgColor(bg_change_div, DEFAULT_COLOR); }); }); 
 .color-option { height: 50px; width: 50px; display: inline-block; margin-left: 10px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="settings"> <!-- HTML will be added here via .js --> </div> <div style="width: 100%; height: 100px;margin-top: 75px;" id="this"> <p>I hope this works.</p> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM