当参数是整数但不是字符串时,javascript onclick函数有效吗?

当参数是整数但不是字符串时,javascript onclick函数有效吗?

问题描述:

echo '<a onclick="load_tags('.$list['id'].')"></a>'

when list[id] is a number, it works. but when list[id] is a word, it does not work. why?

below is some background on the function and what i am doing. although it is not necessary for the purposes of answering this question.

script

function load_tags(id){
        $.post('../php/tags/get_tags.php',{id:id},function(data){
            $('#tags_selected').text(data);
        });
    }

get_tags.php

$tag_id=$_POST['id'];
    echo $tag_id;
    $users_with_this_tag=show_all_users_with_this_tag($tag_id);
    if(count($users_with_this_tag)!=0){
            foreach($users_with_this_tag as $key => $list){
                echo $list['user_id'];
            }
    }else{
        echo'Nobody with this tag';
    }
  echo'&lt; a onclick =“load_tags('。$ list ['id']。'  )“&gt;&lt; / a&gt;'
  code>  pre> 
 
 

list [id] code>是一个数字时,它可以工作。 但是当 list [id] code>是一个单词时,它不起作用。 为什么? p>

下面是关于功能和我正在做的事情的一些背景知识。 虽然没有必要回答这个问题。 p>

脚本 p>

  function load_tags(id){
 $ .post  ('../php/tags/get_tags.php',{id:id},function(data){
 $('#tags_selected')。text(data); 
}); 
} 
   code>  pre> 
 
 

get_tags.php p>

  $ tag_id = $ _ POST ['id']; 
 echo $ tag_id; \  n $ users_with_this_tag = show_all_users_with_this_tag($ tag_id); 
 if(count($ users_with_this_tag)!= 0){
 foreach($ users_with_this_tag as $ key =&gt; $ list){
 echo $ list ['user_id']  ; 
} 
}其他{
 echo'Nobody with this tag'; 
} 
  code>  pre> 
  div>

Just surround load_tags argument with escaped single quotes:

echo '<a onclick="load_tags(\''.$list['id'].'\')"></a>';

Strings should have quotes around them:

echo '<a onclick="load_tags(\"'.$list['id'].'\")"></a>'

Becouse it couses syntax error. Calling JS function with int:

function(123) 
{
 ....
}

And with string:

function('foo') 
{
 ....
}

Without ' it searches for variable under string name (if it's valid variable name).