我的php页面中有一个按钮:
<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>
我该怎么做?
答案 0 :(得分: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>
你可以做到
<script>
$(function() {
$('#myButton').confirmOn('click', function(e, confirmed){
if(confirmed) {
console.log("<?php echo $text ?>");
}
})
});
</script>
使Javascript提醒'someText'。
答案 1 :(得分: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
}
})
});
答案 2 :(得分:0)
您可以在click事件之外声明变量,如下所示:
$(function() {
var confirmed = true;
$('#MyButton').confirmOn('click', function() {
if(confirmed) {
// do stuff
}
});
});
答案 3 :(得分: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
}
})
});
基本上,如果直接在页面上插入PHP变量,则可以使用此方法在javascript中访问变量。如果这不是您想要的,请在评论中告诉我。