javascript onclick无法使用参数

时间:2014-07-22 06:43:07

标签: javascript php onclick

我只是希望用户点击名称,然后弹出(提醒)一些信息。在标签中,如果我没有通过任何参数,它确实提醒某些事情,否则它不会提醒任何事情,即使我放了这样的东西

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

3 个答案:

答案 0 :(得分:0)

首先,我想说我永远不会使用你的编码练习。您不仅会在所有地方都出现引用问题,而且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中的Anonymous函数中。糟糕的HTML练习:

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

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

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

使用不良做法,应该是:

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

您正在将变量传递给JavaScript,而不是String。

onclick='agentsBelow(".$first_levelIdFunction.")'可评估为:

onclick='agentsBelow(youFirstLevelIdFuntionVarResultIsNotaString)'

然而,这不会起作用,因为事件对象会传入。

答案 1 :(得分:-1)

更改此

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

到此:

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

答案 2 :(得分:-1)

更改此

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

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