更改所选div jquery的颜色

时间:2017-01-17 14:38:48

标签: javascript jquery html

我正在尝试创建一个函数,以便当用户点击div然后点击一个按钮背景时,该div的颜色将会改变,因此值必须保存为变量,但我似乎无法得到它因为所有时间的工作都说“存储”变量是未定义的。整页可以在以下网址看到:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content-link2">
  <title>Template 1</title>
  <link href="http://localhost/fyproject/public/templates/css.css" rel="stylesheet" type="text/css">

            <button class="btn btn-default form-control margin color" value="yellow">Background</button>
            <button class="btn btn-default form-control margin color" value="red">Background</button>
  <div class="logo">
    <img class="images" id="image" src="#" alt="Your Logo">
  </div>
  <div contenteditable="true" id="content" class="draggable ui-widget-content refresh ui-draggable ui-draggable-handle" style="position: relative;">
    <p>hlo</p>
  </div>
  <div id="comments">
    <form name="forma">
      <textarea name="commentUser" id="commentUser" class="refresh" cols="40" rows="5">Comments here...
      </textarea>
      <br>
      <input type="submit" value="Ready!" id="send-data">
      <!--onClick="writeComment(e);"-->
      <div id="editTxt" class="refresh" contenteditable="true">
        <p>This text can be by the user.</p>
      </div>
    </form>
  </div>


    </div>

$(document).ready(function() {
  $('.color').click(function() {
    $(storage).css("background-color", $(this).attr("value"));
  });
});

$('#content-link2').on('click', 'div', function(e) {
  var storage = ($(e.target).attr("id"));
});

页面可以在以下网址看到:

https://jsfiddle.net/mbqzL73r/

2 个答案:

答案 0 :(得分:2)

您需要将存储全局设置为两个点击事件的范围

$(document).ready(function() {
  var storage;
  $('.color').click(function() {
    $('#' + storage).css("background-color", $(this).attr("value"));
  });

  $('#content-link2').on('click', 'div', function(e) {
    storage = ($(e.target).attr("id"));
  });
});

More information about js variable scope

答案 1 :(得分:0)

您的存储变量在第二个函数的范围内,您需要将存储声明为全局变量。例如:

var storage = "";
$(document).ready(function() {
  $('.color').click(function() {
    $(storage).css("background-color", $(this).attr("value"));
  });
});

$('#content-link2').on('click', 'div', function(e) {
  storage = ($(e.target).attr("id"));
});