dongxiao1591
dongxiao1591
2016-11-25 16:59

在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';

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dtx3006 dtx3006 5年前

    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'); ?>";
    
    点赞 评论 复制链接分享

相关推荐