简体   繁体   中英

JavaScript escape string issue

I am defining onclick event to aa href based on a condition

Here's my script:

        <script>
          function comment_pop(id)
         {
             alert(id);
             $('#login_ret_url').val('<?php echo base_url();?>idea/view_idea/'+id+'?action=comment');
             ShowModalPopup('div_login');
         }
        </script>


 <div class="rate_image">
            <a href="<?php if(isset($_SESSION['logged_user']))
                      echo base_url().'idea/view_idea/'.$row['idea_slug'].'?action=comment';
                   else
                       echo 'javascript:void(0)';?>" 
              <?php if(!isset($_SESSION['logged_user']))
                      echo "onclick='comment_pop(".$row['idea_slug'].");'";?>>
            <?php echo $total_comment[$key][0]['total_cont'];?>
            </a>
        </div>

The problem rises in the line

echo "onclick='comment_pop(".$row['idea_slug'].");'";?>>

I am trying to concat the function with the variable so that I can send parameter to the JavaScript function but it's not working.

I think I need to use some escape parameters but I am really new to this.

try this

echo "onclick='comment_pop(\'".$row['idea_slug']."\')'";?>>

or making it simple (separeting php and html code)..

 <?php 
        if(isset($_SESSION['logged_user'])){
            $hrefurl=base_url().'idea/view_idea/'.$row['idea_slug'].'?action=comment';
            $onclickurl= "";
        }else{
            $hrefurl = 'javascript:void(0)';
            $onclickurl= 'comment_pop("'.$row['idea_slug'].'");';
  ?>
          <a href="<?php echo $hrefurl;?>" onclick="<?php echo $onclickurl; ?>" >
            <?php echo $total_comment[$key][0]['total_cont'];?>
        </a>

尝试转义“ onclick =“之后的单引号,例如

\'

Your current code echoes the idea_slug without quotes, ie it won't be a JS string (but a variable identifier, a number or something):

…onclick='comment_pop(some_slug);'…

You want to wrap it in quotes presumably:

echo "onclick='comment_pop(\"".$row['idea_slug']."\");'";

so that you get

…onclick='comment_pop("some_slug");'…

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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