2012-11-26 154 views
-1

Q1:我的觀點是創建許多按鈕的行數很多。這裏有一些誤差修改即時通訊:■Javascript onclick函數

<script type="text/javascript"> 
var myArray = []; 

$('#button').click(function(){ 

var value1 = $('#value1').val(); 
var value2 = $('#value1').val(); 
var value3 = $('#value1').val(); 
var newArray = []; 
var newArray[0] = value1; 
var newArray[1] = value2; 
var newArray[2] = value3; 
myArray.push(newArray); 

$("#save").append(
    $("<button>").click(function() { 
     myFunction.apply(null, myArray); 
    }).text("Click me!") 
    ); 
    }); 

}); 

function myFunction(value1,value2,value3) 
{ 
var jsonData = $.ajax({ 
url: "file.php?value1=" + value1 + "&value2=" + value2 + "&value3=" + value3 
dataType: "json", 
async: false 
}).responseText; 
(...) 
} 
//edited: problem maybe found. I said buttons dont do anything because of this. 
OUTPUT: file.php?value1=paul,23,USA&value2=undefined&value3=undefined 
//it seems that value1 gets all values :s 
</script> 


<div id ="save"></div> 

進出口尋找一個解決方案,返回成才這樣的:

如:

<!--<button onclick="myFunction(name,age,country)">Click me</button>--> 
<button onclick="myFunction(paul,23,USA)">Click me</button> 
<button onclick="myFunction(john,23,USA)">Click me</button> 

編輯我的代碼更多的細節

回答

1

是因爲myArray的第一項是一個數組(newArray),您應該只調用一個數組參數嘗試調用下面的函數,它應該工作,

myFunction.apply(null, newArray); 
//or 
myFunction.apply(null, [value1,value2,value3]); 
+0

myFunction.apply(NULL,newArray); ! ;) – pleaseDeleteMe

0

想這有助於:

<div id="save"> 
    </div>  
    <script type="text/javascript"> 
     function addButtons(myArray){ 
      for(i=0;i<myArray.length;i++) 
      { 
       var button = $('<button id="btn_'+i+'" onclick="myFunction(this);">Click me</button>') 
       $(button).data('details',myArray[i]).appendTo("#save"); 
      } 
     } 
     function myFunction(element){ 
      alert($(element).data('details')); 
     } 
    </script>