2016-12-01 72 views
0

我有腳本與多個按鈕,當點擊運行一個PHP腳本通過AJAX。現在我想用按鈕在div中顯示結果。我已經試過這個和父母,但都沒有工作。如何在ajax調用後更新div標籤?

以下示例:點擊時.showme我希望結果顯示在#here div內的同一父級內。

$(document).ready(function() { 
 
    $('.showme').bind('click', function() { 
 

 
    var id = $(this).attr("id"); 
 
    var num = $(this).attr("class"); 
 
    var poststr = "request=" + num + "&moreinfo=" + id; 
 
    $.ajax({ 
 
     url: "../../assets/php/testme.php", 
 
     cache: 0, 
 
     data: poststr, 
 
     success: function(result) { 
 
     $(this).getElementById("here").innerHTML = result; 
 
     } 
 
    }); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class='request_1 showme' id='rating_1'>More stuff 1 
 
    <div id="here"></div> 
 
</div> 
 
<div class='request_2 showme' id='rating_2'>More stuff 2 
 
    <div id="here"></div> 
 
</div> 
 
<div class='request_3 showme' id='rating_3'>More stuff 3 
 
    <div id="here"></div> 
 
</div>

+1

你有沒有在你的瀏覽器的控制檯任何錯誤? – Max

+2

元素'id'在文檔中應該是唯一的。具有相同'id'的多個元素是_invalid_HTML,並且在嘗試使用JS/jQuery定位元素(通常只返回第一個實例)時可能會有未定義的行爲。如果你想用JS/jQuery來定位多個元素,可以使用類來代替。 – jmoerdyk

回答

0

我認爲這會做:

$(document).ready(function() { 
    $('.showme').bind('click', function() { 

     //keep the element reference in a variable to use in ajax success 
     var _this = $(this); 

     var id = $(this).attr("id"); 
     var num = $(this).attr("class"); 
     var poststr = "request=" + num + "&moreinfo=" + id; 
     $.ajax({ 
      url: "../../assets/php/testme.php", 
      cache: 0, 
      data: poststr, 
      success: function (result) { 
       //use the element reference you kept in variable before ajax call instead of $(this) 
       //also use jQuery style, getElementById is undefined if you call after $(this) 
       //.find() will call it's child in any level, also better you use classes instead of using same id multiple times 
       _this.find("#here").html(result); 
      } 
     }); 
    }); 
});