单击元素后Jquery选择器不工作

Jquery selector not working after an element is clicked

本文关键字:工作 选择器 Jquery 元素 单击      更新时间:2023-09-26

我写了一个程序,每次都生成随机颜色。并且"+"按钮应该生成更多的颜色。点击颜色会使其成为容器的背景,但每次点击"+"按钮时,点击颜色对没有影响

这是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);
 }

这是节目的小提琴https://jsfiddle.net/megatroncoder/2o7xL3p1/

fill函数中,您可以重新创建.sel元素,这样它们就不再有点击事件了。他们被认为是新来的。每次在容器中插入新的html时,都必须绑定事件

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("&nbsp;");
  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
    });
  });
}

这是工作小提琴