2012-10-05 33 views
0

所以我想動態生成一些框在屏幕上使用divs,當你點擊一個特定的(name=box1)它執行某些代碼。當他們被硬編碼到我的html下面的代碼工作正常,但現在,因爲我把它們包裝在一個p它需要'this'作爲參考p而不是div。我相信它的第11行需要改變。引用一個特定的元素時,它被包裹在另一個

$(document).ready(function(){ 
    $('#swapboxes').click(function(){ 
     //build the box location array and boxes 
     $('#boxeshere').html(""); 
     for(var i = 0;i < $.gameconfig.numofboxes;i++){ 
      $('<div class="boxes" style="background:#bf3215;height:100px;width:100px;left:'+200*i+'px;position:fixed;" name="box' + i + '" id="' + i + '"/>').appendTo('#boxeshere'); 
     } 
    }); 
    //Execution for clicking on boxes 
    $('.boxes').click(function(){ 
     if(this.attributes["name"].value == "box1"){ 
      $("#info").text("Congrats!!! You win!"); 
     } 
     else{ 
      $("#info").text("I'm sorry, wrong box"); 
     } 
    }); 
}); 
+0

您的問題中沒有足夠的信息供任何人回答。 –

回答

0

點擊應該留在盒子上。

的問題是,.boxes產生頁面加載,點擊#swapboxes的時候,但你試圖點擊事件直接綁定到一種叫做盒子頁面加載時。盒子還不存在。這是行不通的。

使用新的.on()委託方法,您可以綁定到聲明(pageload)時存在的祖先元素(在這種情況下,您已經有了一個用於#swapboxes的jQuery對象),並且委託給目標元素。然後,當#swapbox感覺到點擊(它會因爲事件冒泡),它會查找.boxes元素,並在那裏應用該操作。就像這樣:

$(document).ready(function(){ 
    $('#swapboxes').click(function(){ 
     //build the box location array and boxes 
     $('#boxeshere').html(""); 
     for(var i = 0;i < $.gameconfig.numofboxes;i++){ 
      $('<div class="boxes" style="background:#bf3215;height:100px;width:100px;left:'+200*i+'px;position:fixed;" name="box' + i + '" id="' + i + '"/>').appendTo('#boxeshere'); 
     } 
    }) 
    //Execution for clicking on boxes 
    //delegate from #swapboxes, which exists on page-load, to .boxes: 
    .on('click', '.boxes', function(){ 
     if($this.attr('name') == "box1"){ 
      $("#info").text("Congrats!!! You win!"); 
     } 
     else{ 
      $("#info").text("I'm sorry, wrong box"); 
     }  
    }); 
}); 
0

這裏的問題是該事件沒有附着於新創建的元素.. 因爲新創建的元素仍然不存在在頁面上。

在這樣的你需要委託的情況下,它應該正常工作的情況下..試試這個

$('#boxeshere').on('click', '.boxes' ,function(){ 
     if($(this).prop("name") == "box1"){ 
      $("#info").text("Congrats!!! You win!"); 
     } 
     else{ 
      $("#info").text("I'm sorry, wrong box"); 
     } 
    }); 

在這裏,我們要添加的事件盒子的父母,所以即使將新元素由於事件冒泡添加,新創建的元素將與事件相關聯。

相關問題