2014-01-29 35 views
0

这个jquery函数给我的宽度单击按钮时,但如何可以取代宽度页面加载时。我还需要在php文件中使用with变量。 这个b怎么做?调用jQuery的函数onload和var到php

<script src="//code.jquery.com/jquery-1.10.2.js"></script> 


<button id="getp">Get Paragraph Width</button> 
<button id="getd">Get Document Width</button> 
<button id="getw">Get Window Width</button> 
<div>&nbsp;</div> 
<p> 
    Sample paragraph to test width 
</p> 

<script> 
function showWidth(ele, w) { 
    $("div").text("The width for the " + ele + " is " + w + "px."); 
} 
$("#getp").click(function() { 
    showWidth("paragraph", $("p").width()); 
}); 
$("#getd").click(function() { 
    showWidth("document", $(document).width()); 
}); 
$("#getw").click(function() { 
    showWidth("window", $(window).width()); 
}); 
</script> 

<?='this does not work '.$_GET['w'];?> 
</body> 
</html> 
+1

因为它在客户端和PHP在页面加载服务器端...该宽度你想 –

+0

你的PHP你JavaSript之前甚至被处决执行,你不能在PHP中使用宽度可变到达用户的浏览器。 – George

+0

看到http://jsfiddle.net/arunpjohny/nQkPt/2/ –

回答

0
<input type="hidden" id="hidtext" name="hidtext" value="<?php if(isset($_GET['length'])) echo $_GET['length']; ?>"/> 


<?php 

if(isset($_GET['length'])) 
{ 

    if($_GET['length'] > somevalue) 
    { 
     include('large_menue.php'); 
    } 
    else 
    { 
     include('small_menue.php'); 
    } 

} 

?> 

<script type="text/javascript"> 

if($("#hidtext").val() == "") 
{ 
    $("#hidtext").val($(document).width()); 
    window.location.replace("thispage.php?length="+$(document).width()); 
} 
</script> 

说明:

一旦你打开thispage.php它得到文件的长度,并通过连接网址参数的页面相同的页面重定向。 如果设置了url参数length,则其值存储在hidtext中。 如果hidtext有值,那么页面没有找到宽度并重新加载它。

作为URL参数有文档宽度的值,你可以检查它和inculde相应的文件

+0

谢谢,但我需要提交一个表单或其他东西来获得我的PHP的“hidtext”值。难道没有办法直接将其转换为PHP可变权限吗? – user3214817

+0

不,我已经存储在url参数的值,所以你不想提交表格获得长度 – krishna

+0

阅读我的解释,并尝试实施它,如果你仍然有查询发布它,我会尝试清除它 – krishna

0

您可以按照以下结构;

<script> 
    var w = '400'; 
</script> 
<?php $w = "<script>document.write(w)</script>"?> 
0

你做错了。

不管怎样,添加这个脚本

<script> 

    function showWidth(ele, w) { 
      $("div").text("The width for the " + ele + " is " + w + "px."); 


     window.location =window.location + '?w='+w; 
    } 

</script> 

使用$.ajax发送数据。

0

也许不正确的,unnessessary代码,我不understnad,但这项工作。 :)

<html> 
    <head> 
    <script src="http://code.jquery.com/jquery-1.10.2.js"></script> 
    </head> 
<body> 

<button id="getw" style="visibility:hidden;"></button> 



<?if(!$_REQUEST['width_checked']) {?> 

<script> 
    function showWidth(ele, w) { 
     window.location =window.location + '?width_checked=1&w='+w; 
    } 

    $("#getw").click(function() { 
    showWidth("window", $(window).width()); 

    $('body').load('', function() {}); 
    }).click(); //show the window width on page load 
</script> 
<?}?> 

</body> 
</html>