我编写了一个程序来每次生成随机颜色。而“+”按钮应该会产生更多的颜色。单击颜色会使它成为容器的背景,但每次单击“+”按钮时,单击颜色都没有效果
这是 jquery 代码
var x=$(".container").width();
var l=50-(((25/x)*100)-((10/x)*100));
$(".foot").css({"left":l+"%"});
/*to adjust position*/
$(".foot").click(function(){
fill();
});
var rand,i,z,htm;
$(document).ready(function(){
fill();
/* the following code doesn't work twice after '+' is clicked */
/*-------------------*/
$(".sel").click(function(){
z=$(this).attr("bg");
$(".container").css({"background-color":"#"+z});
});
/*-------------------*/
});
function fill(){
rand=0;
$(".content").html(" ");
htm="";
for(i=0;i<5;i++){
while(rand<100000){
rand=Math.floor(Math.random()*1000000);
}
htm+=
"<"+"div class='sel' bg='"+rand+"'"+">"+
"<"+"div class='content-left' bg='"+rand+"'"+">"+
"<"+"div class='colordot' style='background-color: #"+rand+"'"+">"+"<"+"b"+">"+(i+1)+
"<"+"/"+"b"+">"+
"<"+"/div"+">"+
"<"+"/div"+">"+
"<"+"div class='content-right'"+">"+
"#"+rand+
"<"+"/div"+">"+"
<"+"/div"+">";
rand=0;
}
$(".content").html(htm);
}
这是程序中的 fiddle https://jsfiddle.net/megatroncoder/2o7xL3p1/
最佳答案
在您的 fill
函数中,您重新创建了 .sel
元素,因此它们不再有点击事件。他们认为是新的。每次在容器中插入新的 html 时都必须绑定(bind)事件
var x = $(".container").width();
var l = 50 - (((25 / x) * 100) - ((10 / x) * 100));
$(".foot").css({
"left": l + "%"
});
$(".foot").click(function() {
fill();
});
var rand, i, z, htm;
$(document).ready(function() {
fill();
});
function fill() {
rand = 0;
$(".content").html(" ");
htm = "";
for (i = 0; i < 5; i++) {
while (rand < 100000) {
rand = Math.floor(Math.random() * 1000000);
}
htm +=
"<" + "div class='sel' bg='" + rand + "'" + ">" +
"<" + "div class='content-left' bg='" + rand + "'" + ">" +
"<" + "div class='colordot' style='background-color: #" + rand + "'" + ">" + "<" + "b" + ">" +
(i + 1) +
"<" + "/" + "b" + ">" +
"<" + "/div" + ">" +
"<" + "/div" + ">" +
"<" + "div class='content-right'" + ">" +
"#" + rand +
"<" + "/div" + ">" +
"<" + "/div" + ">";
rand = 0;
z = "";
}
$(".content").html(htm);
bindEvents();
}
function bindEvents() {
$(".sel").on('click', function() {
z = $(this).attr("bg");
$(".container").css({
"background-color": "#" + z
});
});
}
这里正在工作fiddle
关于javascript - 单击元素后 Jquery 选择器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36246580/