2016-03-27 13 views
1

毎回ランダムな色を生成するプログラムを作成しました。 '+'ボタンはより多くの色を生成するはずです。色をクリックすると、そのコンテナの背景になりますが、すべての時間は「+」ボタンをクリックする色をクリックすると、何の効果要素がクリックされた後にJqueryセレクタが機能しない

はここで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/

答えて

2

あなたのfill関数では、.sel要素を再作成するので、クリックイベントはもうありません。彼らは新しいと考えました。あなたは、イベントをバインドする必要がありますが、ここではコンテナに

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

を新しいHTMLを挿入するたびにfiddle

+0

ありがとううまく動作しているようだが取り組んでいます。 –

関連する問題