php 单击 html 链接时获取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16530535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:18:57  来源:igfitidea点击:

Get value when an html link is clicked

phpjavascriptanchor

提问by dhani

Is it possible to get the value of the text in an anchor tag when the link is clicked? e.g if you have <a href="#">Tables</a>is it possible to retrieve the value "Tables" in a variable like a session variable and use it across your pages? I have several categories of items(which are links) and i want to be able to get the value of any category clicked and use it pull products listed in that category from my database. Thanks.

单击链接时是否可以获取锚标记中文本的值?例如,如果您有<a href="#">Tables</a>可能在会话变量等变量中检索值“表”并在您的页面中使用它?我有几个类别的项目(它们是链接),我希望能够获得单击的任何类别的价值,并使用它从我的数据库中拉出该类别中列出的产品。谢谢。

EDIT: This what i tried <a href="#" onclick= "<?php $_SESSION[value] = "Table" ?>">Table</a>But didn't get the value. Apologies, should have posted it earlier

编辑:这是我尝试过的 <a href="#" onclick= "<?php $_SESSION[value] = "Table" ?>">Table</a>但没有得到价值。抱歉,应该早点发布

回答by George Cummins

As posted, your code does not submit so your PHP is never processed:

正如发布的那样,您的代码不会提交,因此您的 PHP 永远不会被处理:

<a href="#"

When you have "#" as the href value, no new request is submitted. However, you can modify your anchor to submit the category back to your PHP script like this:

当您将“#”作为 href 值时,不会提交新请求。但是,您可以修改您的锚点以将类别提交回您的 PHP 脚本,如下所示:

<a href="yourscript.php?category=Table">Table</a>

Then in yourscript.phpyou can read the value using $_GET:

然后yourscript.php你可以使用 $_GET 读取值:

$selected_category = $_GET['category']; // Get 'Table'

To set the value in your session, first be sure that you have started your session near the top of your script:

要在会话中设置该值,首先要确保您已在脚本顶部附近开始会话:

session_start();

then save the value like this:

然后像这样保存值:

$_SESSION['selected_category'] = $_GET['category'];

回答by asafreedman

I'm pretty sure you could try to attach an 'id' or 'class' to it and add an event handler to to that id/class.

我很确定您可以尝试将“id”或“class”附加到它,并向该 id/class 添加一个事件处理程序。

With javascript looking something like:

使用 javascript 看起来像:

$('<your link id>').click(function(ev) {
    ev.preventDefault()
    var content = $(this)[0].innerHTML;
    window.location = '//<your site here>/<php page>?category=' + content;
} 

I apologize for my mix and match JavaScript/jQuery.

我为我的混搭 JavaScript/jQuery 道歉。

Then you can look for in PHP using

然后你可以在 PHP 中使用

$category = $_GET('category');

May be worth it to escape user specified data if you plan on doing lookups with it.

如果您打算使用它进行查找,那么转义用户指定的数据可能是值得的。