2017-07-29 58 views
0

任何上級可以幫助我解決下面的問題。我的腳本錯了。
我的問題是,我如何從循環內部獲得一個值,當循環內部還有一個按鈕和按鈕時。 非常感謝我如何定義哪個按鈕從一個循環內點擊即可

$(document).ready(function(){ 
 
    var btn = document.getElementsByid("button"); 
 

 
    for (var i = 0; i < document.getElementsByid("button").length; i++) { 
 
    
 
    /* my problem in here. How I define which one of the button 
 
    onclick then get value from the <input type=""hidden"> */ 
 
    btn[i].onclick = function() { 
 
    
 
     var hd1 = $("#hidden1"+i).val(); 
 
     
 
     $.get('try.php', { 
 
     sendResult: hd1 
 
     }, function(data) { 
 
     $('#returnResult').html(data); 
 
     }); 
 
     
 
    }; 
 
    }; 
 
});
<!-- I want sending one of the value from '$arrayValue'. --> 
 
<?php 
 
    $arrayValue = array(a, b, c); 
 

 
    foreach($arrayValue as $eachResult) { 
 

 
    echo ' 
 
     <input type="hidden" id="hidden1" value="'.$eachResult["arrayValue"].'"> 
 
    
 
     <button type="button" id="button"></button> 
 
    ';} 
 

 
?>

回答

0

使用.prev().val()。而.getElementsByid("button")是無效的,應該是.getElementsByTagName("button")

$(document).ready(function() { 
 
    var btn = document.getElementsByTagName("button"); 
 

 
    for(var i = 0; i < btn.length; i++) { 
 

 
    /* my problem in here. How I define which one of the button 
 
    onclick then get value from the <input type=""hidden"> */ 
 
    btn[i].onclick = function() { 
 

 
     var hd1 = $("#hidden1" + i).val(); 
 
     console.log($(this).prev().val()) 
 
     $.get('try.php', { 
 
     sendResult: hd1 
 
     }, function(data) { 
 
     $('#returnResult').html(data); 
 
     }); 
 

 
    }; 
 
    }; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<input type="hidden" id="hidden1" value="hidden value 1"> 
 
<button type="button" id="button">btn1</button> 
 

 
<input type="hidden" id="hidden1" value="hidden value 2"> 
 
<button type="button" id="button">btn2</button>

+0

非常感謝回答我的問題,但仍然無法爲我的劇本工作。我更改爲使用類並使用getElementFromClassName,但仍然只能從循環中獲取最後一個值。謝謝 – Fun