2010-01-31 123 views
2

我在點擊事件時遇到問題。 當調用insertIntoInsertHolder()時,它會添加一個指向div#swf_insert_holder內容的鏈接 - 然後在下面創建click事件。但事件不會觸發。php和jquery點擊事件問題

$javascript = "javascript:;"; 
$swf_insert_box_link = "swf_insert_box_link"; 

echo " 

function insertIntoInsertHolder(filename) { 
$('#swf_insert_holder').append('<a href=" . $javascript . " class=" .  $swf_insert_box_link . ">go</a>'); 
//produces: <a href="javascript:;" class="swf_insert_box_link">go</a>    
    } 

$('a.swf_insert_box_link').click(function() { 
alert('hello!!'); //for testing  
}); 

在此先感謝!

+2

難道這可能是因爲在你的代碼很多語法錯誤? – 2010-01-31 23:44:47

+2

@ Chacha102可能,所以一個很好的答案顯示問題將有助於更多的IMO。 – 2010-01-31 23:46:58

回答

0

使用,這將導致它的工作:

<?php 
$javascript = "javascript:;"; 
$swf_insert_box_link = "swf_insert_box_link"; 

echo <<<JS 
function insertIntoInsertHolder(filename) { 
    \$('#swf_insert_holder').append('<a href="$javascript" class="$swf_insert_box_link">go</a>'); 
    // produces: <a href="javascript:;" class="swf_insert_box_link">go</a>    
} 

\$('a.swf_insert_box_link').live('click', function() { 
    alert('hello!!'); //for testing  
}); 
JS; 
?> 

的重要部分是#1,修復所有PHP語法錯誤和#2,使用live而不是點擊,因此您可以在之前定義事件回調該元素實際存在。

+0

當我嘗試<<< JS並關閉它與JS;我在文件的最後一行獲得了一個語法(它在這裏有更多的東西)如果我可以使用<<< JS那將是虔誠的 – 2010-02-01 00:10:32

+0

@unknown不能有空格(製表符,空格,等等)之間的最後'JS;'和行的開始。否則它不會知道heredoc結束(heredoc是'<<< JS ... JS;') – 2010-02-01 01:52:55

1

還必須注意,事件處理程序已附加到現有元素。所以,當你的'click'事件附加到一個.wf_insert_box_link時,該元素應該存在。爲了有連接到給定現有的選擇和相同的選擇匹配任何新的內容時,用戶生活() - http://api.jquery.com/live/

0

元素在附加事件偵聽器之前必須存在。你能忍受()函數,而不是點擊()這樣做(需要jQuery的1.3+),或結合而創造元素,像這樣:

function insertIntoInsertHolder(filename) { 
    $('#swf_insert_holder').append(
     $('<a>') 
      .attr('href', '<?php echo $javascript; ?>') 
      .addClass('<?php echo $swf_insert_box_link;?>') 
      .text('go') 
      .click(function() { alert('hello!!'); }); 
    ); 
}