2013-04-24 129 views
4

這是我的HTML和PHP代碼爲什麼這不會工作?如何使這項工作?

Colorbox很好,它也顯示按鈕。

//This is the Colorbox code 
<div style="display: none"> 
<div id="remove"> 
    <h1>Are you sure you wish to remove this product</h1> 
    <h2>Enter Captcha below to confirm</h2> //Just a Captcha-like behavior 
    <input type="text" value="<?php echo $captcha_value; ?>" id="display" readonly ><br /> <br> 
    <input type="text" name="captcha" value="" id="input" maxlength=6/> <br> <br> 
</div> 
</div> 

//To Display all products 
<?php foreach ($products as $product) { ?> 
<td> 
    <div> 
    <img src="<?php echo $product['image']; ?>"/> 
    </div> 
    <div> 
    <a onClick="loadColor(<?php echo $product['opv_id']; ?>)" class="remove-item"> 
     <img src="<?php echo $product['product_remove_image']; ?>"/> 
    </a> //To know which product's link was clicked 
    </div> 
</td> 
<?php } ?> 

//loadColor function which will append a button to Colorbox 
<script type="text/javascript"> 
function loadColor(opv_id) { //To create a button and append to the colorbox and call colorbox 
    $('#remove-product').remove(); 
    string = '<button value="' + opv_id + '" id="remove-product">Submit</button>'; 
    $(string).appendTo('#remove'); 
    jQuery.colorbox({inline: true, href:"#remove", width:"50%"}); 
} 
</script> 

<script type="text/javascript"> 
$('#remove-product').click(function() { 
    alert('Clicked'); 
    //Do something here!! 
}) 
</script> 

明白了:)

那麼,有沒有其他更簡單的方式來實現我試過上面做什麼?

+0

尋找 「事件代理」。 – elclanrs 2013-04-24 05:12:17

+0

[jQuery - Click事件不能在動態生成的元素上工作]的可能重複(http://stackoverflow.com/questions/6658752/jquery-click-event-doesnt-work-on-dynamically-generated-elements) – undefined 2013-04-24 05:13:52

回答

4

您需要使用事件代表團動態添加元素:

$('#remove').on("click", '#remove-product', function() { 
    alert('Clicked'); 
    //Do something here!! 
}); 

檢查documentation

+0

非常感謝你。請看我編輯的問題。 – Razor 2013-04-24 05:23:42

+0

@Razor你已經以正確的方式完成了:) – Eli 2013-04-24 05:29:38