2016-07-05 14 views
1

我想警告用戶鏈接上的每個用戶的個人id點擊html。因此,每個用戶都將從數據庫中獲取並作爲鏈接顯示在頁面上。此外,由於它們具有唯一的電子郵件ID,因此我試圖在單擊該用戶鏈接時警告他們的電子郵件。我的問題是,無論何時點擊第一個,它都會提醒電子郵件,但點擊後的第二個,第三個等不會彈出任何警報。後續定位標記不工作在HTML/PHP

下面是代碼片段:

<strong><a href="#" id="post_user" name="post_user" class="<?php echo $messagePost_Email; ?>"><?php echo $messagePost_FirstName.' '.$messagePost_LastName;?></a></strong> 

jQuery的

<script type="text/javascript"> 

    $(function(){ 
    $("#post_user").click(function(){ 
     var element = $(this); 
     var emailID = element.attr("class"); 
     var info = "emailID="+emailID; 
     alert(info); 
     $.ajax({ 
     tpye : "POST", 
     url : "navigate.php", 
     data: info, 
     success : function(){ 

     } 
     }) 
    }) 
    }) 

</script> 

任何建議將是很大的幫助,因爲我無法弄清楚的根本原因這種行爲。

回答

1

的問題是,你可能使用每一個錨元素相同id屬性:

<strong><a href="#" id="post_user" ... 

id屬性,就是要一個標識符因此必須是唯一的

你應該擺脫id屬性(如果你不使用它的其他地方)和作爲jQuery選擇器使用class來代替。例如:

<strong><a href="#" class="post_user" ... 

emailID(用戶ID)店,因爲它是在做這樣的事情的更清晰的方式元素的data attribute。這是data屬性最適合使用的內容。

<a href="#" class="post_user" data-emailID="<?php echo $messagePost_Email; ?>" ... 

的jQuery:

$(function(){ 
    $(".post_user").click(function(){ 
     var emailID = $(this).attr("data-emailID"); 
     // or: 
     // emailID = $(this).data("emailID"); 
     alert(emailID); 
     $.ajax({ 
      type : "POST", 
      url  : "navigate.php", 
      data : {emailID : emailID}, 
      success : function(response){ 
       // ... do anything with "response" ... 
      } 
     }) 
    }) 
}) 
+0

工作像一個魅力,謝謝ARTUR。 –

+0

我的另一個問題是,如果我想要獲取data-emailID屬性的值而不是使用jquery,請使用$ _POST,因爲$ _POST只接受名稱屬性值,所以我該如何操作。 –

+0

至於HTML5 - 錨標記中的'name'屬性無效。你可以使用它作爲表單元素,例如'input' /'select' /'checkbox'/etc ... –

0

嘗試這種方式

<script src="jquery.min.js"></script> 
<strong><a href="#" id="post_user1" name='[email protected]'>user1</a></strong> 
<strong><a href="#" id="post_user2" name='[email protected]'>user2</a></strong> 
<strong><a href="#" id="post_user3" name='[email protected]'>user3</a></strong> 

<script type="text/javascript"> 

$("a").click(function(event){ 
    // Capture the href from the selected link... 
    ids = ['post_user1', 'post_user2'];//add anchor id, at which you want to call this function. 
    var id = this.id; 
    if($.inArray(id, ids) != -1) {// check this id is in list. 
     var email = this.name; 
     var info = "emailID="+email; 
     alert(email); 
     $.ajax({ 
      tpye : "POST", 
      url : "navigate.php", 
      data: info, 
      success : function(){ 

     } 
     }); 
    } 
    return false; // not needed if you want the link to execute normally... 
}); 

</script> 
+0

[?爲什麼使用的onClick()在HTML中的壞習慣(http://stackoverflow.com/questions/5871640/why-is-using-onclick-在-html-a-bad-practice) –