2011-05-30 67 views
1

在PHP頁面我有這樣發送參數到jQuery函數

echo '<tr><td><a href="#" onclick="myFunction('.$id.')">Click</a></td></tr>'; 

$id一個表中的幾行被動態地從數據庫中生成

所以我要定義的jQuery的功能,但將參數傳遞給jQuery函數。

對於每一個按鈕,我點擊會有通過

回答

1

爲什麼不使用ID爲這樣的鏈接標識另一個參數:

<a href="#" id="<?=$id?>" class="myjquerylink">Click me</a> 

在jQuery中可以綁定到像onclick事件這樣的:

 
// Execute on load 
$(document).ready(function(){ 
    // Bind to click 
    $('a.myjquerylink').click(function(){ 
     // Get the id 
     var id = $(this).attr('id'); 

     // Do something with the id. 
     doSomething(id); 
    }); 
}); 
0

您需要修改HTML一點:

echo '<tr><td><a class="someclass" href="#" id='".$id.'">Click</a></td></tr>'; 

然後你可以通過它在JQuery中的類來調用它,並做你想做的事: 「$(this)」將是對被點擊項的引用。

$(".someclass").live('click',function(e){ e.preventDefault(); alert($(this).text())}); 
+0

thx,我修正了錯字,並改爲val()to t ext() - 我剛剛從隨機源代碼中複製。 – balint 2011-05-30 21:38:59

0

你究竟想幹什麼?
下面是一個示例功能(它不使用jQuery!),提醒該鏈接已被按下,並停止傳播事件的用戶,所以它不會跳轉到另一個頁面上點擊

<script type="text/javascript"> 
    function myFunction(param) { 
     alert('The button with the id ' + param + ' has been pressed!'); 
     return false; 
    } 
</script> 
0

好在一個骯髒的方式,你可以指定你的ID在相對標籤是這樣的:

echo '<tr><td><a href="#" rel="'.$id.'" class="mylink">Click</a></td></tr>'; 

比你可以在jQuery的搜索則myButton類的事件添加到它:

$("a.mylink").click(function(){ 
    alert($(this).attr('rel')); 
}); 

所以在這種情況下$(this).attr('rel')應該是你的ID。

0

正如其他海報開始說的,綁定一個功能到一個事件。假設你分配一個CSS類的一個標籤,使其更容易:

echo '<tr><td><a class="specialLinks" href="#" onclick="myFunction('.$id.')">Click</a></td></tr>'; 

那麼你會綁定到你的類是這樣的:

$(「 specialLink‘)綁定(’點擊」,功能(){ this.preventDefault(); 警報($(this.attr( 「ID」)); });