2014-01-15 67 views
0

我在我的PHP頁面有一個按鈕:一個變量傳遞給JavaScript函數

<button id="myButton">Delete me</button> 

,並在頁面我有我想傳遞給一個JavaScript函數的變量,這是我的JS代碼:

<script> 
     $(function() { 
      $('#myButton').confirmOn('click', function(e, confirmed){ 
       if(confirmed) { 
        //Here I'll use the variable 
       } 

      }) 

     }); 

</script> 

我該怎麼做?

+2

你能提供關於變量的更多細節嗎?例如。你可以在哪裏訪問它? –

+0

你想要什麼? PHP變量爲Javascript? – Cilan

回答

0

我想你可能會想要把一個變量,通過PHP在您的按鈕,並把它傳遞給你的功能使用jQuery data。檢查了這一點:

<button data-confirmed="<?php echo $confirmed; ?>" id="myButton">Delete me</button> 

而在你的JS:

 $(function() { 
      $('#myButton').on('click', function(e){ 
       // get jquery object access to the button 
       var $thisButton = $(this); 

       // this gets that data directly from the HTML 
       var confirmed = $thisButton.data('confirmed'); 

       if(confirmed) { 
        //Here I'll use the variable 
       } 

      }) 
     }); 

基本上,你可以訪問使用此方法在JavaScript中的變量,如果你插PHP增值經銷商直接在頁面上。如果這不是你要找的,請在評論中告訴我。

0

假設你正在談論傳遞PHP變量JavaScript,您可以編寫頁面的時候做到這一點,例如:

<?php 

$passThis = 'Passing' 

?> 

<script language="javascript" type="text/javascript"> 
    var sStr = "My name is <?php echo $passThis ?>."; 

    document.write(sStr); 
</script> 

你也可以得到整數值,做這樣的事情

$integerValue = 5; 
var int = "<?php echo $integerValue; ?>"; 
int = parseInt(int); 

通過修改這一點,你可以用它來傳遞更多類型的變量,所以假設你有這樣的事情:

<?php 
    $text = 'someText'; 
?> 

<script> 
     $(function() { 
      $('#myButton').confirmOn('click', function(e, confirmed){ 
       if(confirmed) { 
        //Here I'll use the variable 
       } 

      }) 

     }); 

</script> 

你可以做

​​

使Javascript提醒'someText'。

0
<button id="myButton">Delete me</button> 
<input type="hidden" name="variable" id="variable" value=2> 

<script> 
    $(function() { 
     $('#myButton').confirmOn('click', function(e, confirmed){ 
      if(confirmed) {= 
       alert(document.getElementById('variable').value); 
//Here I'll use the variable 
      } 

     }) 

    }); 

0

可以聲明單擊事件外的變量,像這樣:

$(function() { 
    var confirmed = true; 

    $('#MyButton').confirmOn('click', function() { 
    if(confirmed) { 
     // do stuff 
    } 
    }); 
});