我最初尝试使用 jQuery 的 .css() 来执行此任务,但失败了。我尝试了几种方法,但都失败了。我更愿意学习如何使用 jquery 的库执行此功能。 jQuery UI 用于可拖动和可调整大小的 UI.My
我当前的代码:
<div id="p1"></div>
<link rel="stylesheet" href="script\jquery-ui-1.10.3.smoothness\css\smoothness\jquery-ui-1.10.3.custom.min.css" />
<script src="script/jquery-1.10.1.min.js"></script>
<script src="script/jquery-ui-1.10.3/ui/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="style/style.css">
<script type="text/javascript">
counter = 0;
$(function() {
$(document).on("click",'#addNewCo',function(e){
e.preventDefault();
var newCo = $('<div class="note" id="note'+counter+'" onclick="changecolor("note'+counter+'","EB0955")">note</div>').draggable({ scroll: true, scrollSpeed: 100 }).resizable();
$('#area').append(newCo);
});
});
function changecolor(id,color) {
document.getElementById(id).style.backgroundColor = '#'+color;
}
</script>
<a id="addNewCo" href="javascript:void(0);"><button>New Note</button></a>
<div id="area"></div>
最佳答案
不要为您的新元素使用内联 JavaScript,使用 .on()
进行委托(delegate),就像您在代码的其他部分中所做的那样。尝试:
$(function () {
$(document).on("click", '#addNewCo', function (e) {
e.preventDefault();
var newCo = $('<div class="note" id="note' + counter + '")">note</div>').draggable({
scroll: true,
scrollSpeed: 100
}).resizable();
$('#area').append(newCo);
counter++;
});
$(document).on("click", '.note', function () {
changecolor($(this).attr('id'), 'EB0955');
});
});
您还忘记了增加计数器。您还可以将 jQuery 用于第二个函数:
function changecolor(id, color) {
$('#'+id).css('backgroundColor', '#' + color);
}
关于javascript - 如何在 jquery 创建后动态更改 div 的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16988535/