单击一个元素后,Jquery选择器不起作用

时间:2016-03-27 11:00:07

标签: javascript jquery html

我写过一个程序,每次都会生成随机颜色。并且' +'按钮应该生成更多的颜色。单击颜色将使其成为容器的背景,但每次都是' +'点击按钮点击颜色无效

这里是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/

1 个答案:

答案 0 :(得分:2)

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

这是有效的fiddle