用点击功能将php变量传递给模态窗口 [英] passing php variable to modal window with click function

查看:46
本文介绍了用点击功能将php变量传递给模态窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单击功能,可以启动模式窗口.在模态窗口内部,我加载modal_window.php.点击功能如下所示:

I have a click function that launches a modal window. Inside of the modal window I load modal_window.php. The click function look like this:

$('a#testmodal').click(function(e){
<? $id = $_GET['id']; ?>
varid = <? echo $id; ?>;
        $.get('modal_window.php?id=' + varid, function(data){
modal.open({content: data});});
                e.preventDefault();
            });

我用来触发它的链接看起来像这样:

And the link that I'm using to trigger it looks like this:

<a id="testmodal" href="modal_2.php?id=5">Test</a>

奇怪的是,当我第一次单击链接时,什么也没有发生.但是,当我第二次单击它时,一切都会正常进行.造成这种情况的原因似乎是我的代码的jQuery部分在设置php变量$ id之前第一次运行(先运行jquery部分,然后运行php部分).然后,当我第二次单击链接时(此时已在click函数中设置了PHP变量$ id),一切正常.

The strange thing is when I click on the link the first time nothing happens. However when I click on it the second time everything works as it should. The reason for this seems to be that the jquery piece of my code runs the first time before the php variable $id is set (the jquery section runs and then the php section runs). Then when I click on the link the second time (the php variable $id within the click function is set at this point) everything works perfectly.

所以我的问题是有没有其他方法可以将变量从我的链接传递给不依赖php的click函数.像这样:

So my question is is there a different way to pass a variable from my link to my click function that does not depend on php. Something like this:

<a id="testmodal" href="" var id ="5">Test</a>

推荐答案

您的代码第一次无法使用,因为$_GET上没有任何数据,因此该函数将出现语法错误,并且链接将正常"地行动.第二次单击时,您将具有id参数,因此它将打开模式.

Your code won't work the first time because there won't be any data on $_GET so the function will have a syntax error and the link will act "normally". On second click you will have the id parameter so it will open the modal.

现在,我不太了解实现的逻辑,但是如果您只想将值传递给点击处理程序,则可以使用数据属性:

Now, I don't quite understand the logic behind your implementation but if you simply want to pass a value to your click handler you could use data attributes:

HTML

<a id="testmodal" href="#" data-id ="5">Test</a>

JavaScript

$('#testmodal').click(function(e){
    e.preventDefault();
    $.get('modal_window.php?id=' + $(this).data('id'), function(data){
        modal.open({content: data});}); 
});

那行得通,但是我假设您将有多个链接到不同的模式窗口,因此您可能希望为链接提供一个类,并将其用作点击处理程序中的选择器,例如:

That would work, but I assume you'll have multiple links to different modal windows so you may want to give a class to your links and use that as your selector in the click handler, something like:

$('.open-modal').click(function(e){
    ...
});

这篇关于用点击功能将php变量传递给模态窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆