dongxiao1591
2016-11-25 16:59
浏览 407
已采纳

在jQuery中使用PHP变量作为变量

I'm having a hard time understanding how to import a specific variable for use with jQuery.

Some links on a Wordpress theme are using

<?php  if( get_post_meta($post->ID, "portfolio_link", true) ): ?> 
            <h1 class="portfolio-title">
                <a target="_blank" href="<?php the_field('portfolio_link'); ?>">
                    <?php the_field('portfolio_title'); ?> <span class="sosa-icon">p</span>
                </a>
            </h1>
            <!--get PDF if not empty-->
        <?php else: ?>
            <h1 class="portfolio-title"><?php the_field('portfolio_title'); ?></h1>
<?php endif; ?>

As you can see the href is set as

href="<?php the_field('portfolio_link'); ?>"

Now I have a jQuery script as follows

    <script>
  <?php  if( get_post_meta($post->ID, "portfolio_link", true) ): ?> 
  <?php

$phpVar = 'http://www.google.com';
  echo "var phpVariable = '{$phpVar}';";

?>
  jQuery(".box").click(function() {

    window.open(phpVariable);
});

  <?php endif; ?>
</script>

This script currently works. It opens google in a new tab as a placeholder until I know how to make it open the same result as the href.

Now what I can't understand is how to set '$phpVar' to have the same effect as the 'href' I showed before instead of 'http://www.google.com';

图片转代码服务由CSDN问答提供 功能建议

我很难理解如何导入特定变量以便与jQuery一起使用。 \ n

Wordpress主题上的一些链接正在使用

 &lt;?php if(get_post_meta($ post-&gt; ID,“portfolio_link”,true))  :?&gt;  
&lt; h1 class =“portfolio-title”&gt; 
&lt; a target =“_ blank”href =“&lt;?php the_field('portfolio_link');?&gt;”&gt; 
&lt;?php  the_field( 'portfolio_title');  ?&GT;  &lt; span class =“sosa-icon”&gt; p&lt; / span&gt; 
&lt; / a&gt; 
&lt; / h1&gt; 
&lt;! - 如果不为空则获取PDF  - &gt; 
&lt;  ;?php else:?&gt; 
&lt; h1 class =“portfolio-title”&gt;&lt;?php the_field('portfolio_title');  ?&gt;&lt; / h1&gt; 
&lt;?php endif;  ?&gt; 
   
 
 

如您所见,href设置为

  href =“&lt;?php  the_field('portfolio_link');?&gt;“
   
 
 

现在我有一个jQuery脚本如下

   &lt; script&gt; 
&lt;?php if(get_post_meta($ post-&gt; ID,“portfolio_link”,true)):?&gt;  
&lt;?php 
 
 $ phpVar ='http://www.google.com'; 
 echo“var phpVariable ='{$ phpVar}';”; 
 
?&gt; 
  jQuery(“。box”)。click(function(){
 
 window.open(phpVariable); 
}); 
 
&lt;?php endif;  ?&gt; 
&lt; / script&gt; 
   
 
 

此脚本目前有效。 它在一个新的标签中打开谷歌作为占位符,直到我知道如何使它打开与href相同的结果。

现在我无法理解的是如何将'$ phpVar'设置为与之前显示的'href'相同,而不是' http://www.google.com ';

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dtx3006 2016-11-25 17:10
    已采纳

    Not sure just how the WordPress handling of this is, but given that the_field('portfolio_title'); returns a valid URL, you can simply assign the JavaScript variable the output of this variable.

    var phpVariable = "<?php the_field('portfolio_link'); ?>";
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题