Quotes javascript (jquery) -html-php

I came across this question:

Example

<td>
    <span style="cursor:pointer;" onclick="$(this).parent().html('<input type=\'text\' value=\'asdasd\' onkeydown=\'javascript:if(char_click(event)==13){send_ajax_settings($(this),'title' ,'3')}\'>');">
        <?=$result['settings_title']?>
    </span>
</td>

It looks great, but in the browser I get the message "Uncaught SyntaxError: Unexpected identifier" on this line (chrome list):

<span style="cursor:pointer;" onclick="$(this).parent().html('input type=\'text\' value=\'asdasd\' onkeydown=\'javascript:if(char_click(event)==13){send_ajax_settings($(this),'title' ,'3')}\'>');">asdasd</span>

Please help me - if anyone had such problems before. Where am I mistaken? Maybe it is better to do this via PHP echo (I think not :))?

+3
source share
2 answers

You did not escape the apostrophes in 'this' and '3'.
The correct markup is this:

<span style="cursor:pointer;" onclick="$(this).parent().html('input type=\'text\' value=\'asdasd\' onkeydown=\'javascript:if(char_click(event)==13){send_ajax_settings($(this),\'title\' ,\'3\')}\'>');">asdasd</span>

However, such binding events are very bad practice and lead to the type of errors you just had. You should do it like this:

 <span style="cursor:pointer;" class="spanClass" data-param1="title" data-param2="3">asdasd</span>
 <span style="cursor:pointer;" class="spanClass" data-param1="title2" data-param2="5">asdasd</span>
 ... more spans generated dynamically

and do the following:

   $(document).ready(function(){
     $(".spanClass").click(function(){
          var param1 = $(this).attr("data-param1");
          var param2 = $(this).attr("data-param2");
          $('<input type="text" value="asdasd" />').keydown(function(event){
            if(char_click(event)==13) {
               send_ajax_settings($(this), param1 , param2));
            }
          }).appendTo($(this).parent());
      });
    });

, javascript html , .

, .

+3

, - escape- send_ajax, :

<span style="cursor:pointer;" onclick="$(this).parent().html('input type=\'text\' value=\'asdasd\' onkeydown=\'javascript:if(char_click(event)==13){send_ajax_settings($(this),\'title\' ,\'3\')}\'>');">asdasd</span>

, , onclick- , . , , , .

+3