javascript - 单击元素后 Jquery 选择器不起作用

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

这是程序中的 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("&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

关于javascript - 单击元素后 Jquery 选择器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36246580/

相关文章:

javascript - 如何将 FileSaver.js 与 Canvas 一起使用

javascript - 刷新后保留数据AngularJS

javascript - 更改 Javascript setInterval

javascript - 删除 jquery 中单击菜单后的菜单悬停操作

javascript - 防止默认后重新启用提交

javascript - 为什么 'drop' 事件没有在此网页上触发?

javascript - Android 版本上的 React Native 应用程序显示 "Unable to load script from assets' index.android.bundle'“需要重新启动系统

jquery - 权限被拒绝 - 在 jquery Horizo​​ntal Accordion 中打开 Vimeo

html - 我无法在 Bootstrap DIV 的底部获取图像

javascript - 如何增加 sIFR 文本的抗锯齿/模糊效果?