Javascript onclick不能处理参数


javascript onclick not working with parameters

我只是想让用户点击一个名字,然后它弹出(警报)一些信息。在a标签中如果我不传递任何参数它会发出警告,否则它不会发出警告,即使我输入这样的

<a href='javascript:sayThis('hi');'>

这是我的html代码(由一些PHP生成):

PHP:

 function showThis($color, $withFunctionYesOrNo, $first_levelIdFunction, $first_levelNameFunction, $first_levelLastNameFunction, $agent_email){
    if($withFunctionYesOrNo == 'yes'){
    $showThis =  "<br>
        <div>
            <div style='margin-left:5%; border-left:6px solid ".$color."'>------
                <a href='javascript:sayThis('".$agent_email."');'>
                ".$first_levelLastNameFunction.", ".$first_levelNameFunction." (ID: ".$first_levelIdFunction.")
                </a>
                <input type='submit' class='more' id='more' value='+' onclick='agentsBelow(".$first_levelIdFunction.")'>
            </div>
        <div style='margin-left:7%;' id=".$first_levelIdFunction."></div>
        </div>";
}
return $showThis;
}

这是我的JS代码:

function sayThis(email){
alert(email);
}

首先,我想说我永远不会使用您的编码实践。你不仅有报价问题,但onclick事件对象被传递给你的事件处理程序agentsBelow()。在这些情况下,我这样写代码:

document.getElementById('more').onclick = function(e){
  e = e || event; // don't even need to use the `e` argument above or this if not using the Event Object
  agentsBelow('whatever');
}

真的,我展示的风格是你应该编码的方式,你的JavaScript是从你的HTML分开。当然,如果您坚持,也可以将函数包装在HTML中的匿名函数中。错误的HTML实践:

onclick='function(){agentsBelow('"you have String issues too'")}'

请注意,您不需要在双引号中连接。顺便说一下:

onclick='agentsBelow(".$first_levelIdFunction.")'
使用

的不良做法,应该是:

onclick='function(){agentsBelow('"$first_levelIdFunction'")}'

你正在传递一个变量给你的JavaScript,而不是一个字符串。

onclick='agentsBelow(".$first_levelIdFunction.")'可求值为:

onclick='agentsBelow(youFirstLevelIdFuntionVarResultIsNotaString)'

仍然不能工作,因为事件对象会传入

修改

<a href='javascript:sayThis('hi');'>

:

<a href='javascript:sayThis("hi");'>

change this

<a href='javascript:sayThis('".$agent_email."');'>

<a href='javascript:sayThis('"".$agent_email."'");'>