简体   繁体   English

使用PHP $ _GET执行JavaScript代码

[英]Execute JavaScript code with PHP $_GET

I have a bit of coding that displays div's when requested through a link, now I want to be able to link to that page, and execute the JavaScript with the parameter given through the url in PHP. 我有一些编码,当通过链接请求时显示div,现在,我希望能够链接到该页面,并使用PHP中通过url提供的参数执行JavaScript。

The JavaScript displays and closes div's when requested through links. 通过链接请求时,JavaScript显示和关闭div。

Link example: 链接示例:

<a href="#div1" class="selectType">Click here for div1</a>
<a href="#div2" class="selectType">Click here for div2</a>
<a href="#div3" class="selectType">Click here for div3</a>

JavaScript code: JavaScript代码:

$('.selectType').on('click', function(e){
    e.preventDefault();
    var targetDiv = $($(this).attr('href'));
    if(!targetDiv.is(':visible')){
        $('.hide').slideUp();
        targetDiv.slideDown();
    }else{
        $('.hide').slideUp();
    }
});

css for div: div的CSS:

.hide{display:none;}

div code: div代码:

<div id="div1" class="hide">Text in div1</div>
<div id="div2" class="hide">Text in div2</div>
<div id="div3" class="hide">Text in div3</div>

I want to give the URL a link like so: 我想给URL像这样的链接:

http://www.example.com/pages/index.php?pageid=div2

When that page is visited, the JavaScript will execute as if the link "Click here for div2" was pressed, so that div2 pops up. 当访问该页面时,将执行JavaScript,就像按下链接“ Click here for div2”一样,从而弹出div2。

I have no idea where to get started, as in, I do know how to grab the $_GET['pageid'] variable, but no clue how to combine it with the JavaScript into displaying the requested div. 我不知道从哪里开始,因为我确实知道如何获取$_GET['pageid']变量,但是不知道如何将其与JavaScript结合以显示所请求的div。

Thanks ahead! 谢谢你!

First change your hide/show into a function to save repeating code... ie: 首先将您的隐藏/显示更改为保存重复代码的功能...即:

var toggleSelectType = function(target) {
    var targetDiv = $(target);

    if (!targetDiv.is(':visible')) {
        $('.hide').slideUp();
        targetDiv.slideDown();
    } else {
        $('.hide').slideUp();
    }
};

$('.selectType').on('click', function(e){
    e.preventDefault();
    toggleSelectType($(this).attr('href'));
});

Add a function that helps you grab query string values such as: ( How can I get query string values in JavaScript? ) ** credit 添加一个可帮助您获取查询字符串值的函数,例如:( 如何获取JavaScript中的查询字符串值?

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

Then when the page loads check for the value of pageid and run your function: 然后,在页面加载时检查pageid的值并运行您的函数:

var pageId = getParameterByName('pageid');
toggleSelectType('#'+pageId);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM