gpt4 book ai didi

javascript - 更改所选div jquery的颜色

转载 作者:行者123 更新时间:2023-11-27 23:19:43 24 4
gpt4 key购买 nike

我正在尝试创建一个函数,以便当用户点击一个 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/

最佳答案

您需要为两个点击事件的作用域设置全局存储

$(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

关于javascript - 更改所选div jquery的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41699912/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com