JavaScript onclick 函数在参数为整数而不是字符串时工作


javascript onclick function works when parameter is integer but not string?

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

list[id]是一个数字时,它起作用了。但是当list[id]是一个词时,它就不起作用了。为什么?

以下是有关该功能的一些背景和我正在做的事情。 尽管对于回答这个问题的目的不是必需的。

脚本

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

只需用转义的单引号将load_tags参数括起来:

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

字符串周围应该有引号:

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

因为它使用语法错误。使用 int 调用 JS 函数:

function(123) 
{
 ....
}

并带有字符串:

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

如果没有 ',它将在字符串名称下搜索变量(如果它是有效的变量名称)。