【问题标题】:OnClick event doesn't work in ChromeOnClick 事件在 Chrome 中不起作用
【发布时间】:2023-10-01 13:08:01
【问题描述】:

我编写了以下代码以在我的页面上有一个选择列表:

<select id='defchtype' class='selectpicker form-control' style='width:80%;'>
    <option id='Pie' onClick='changechart(".$_GET['id'].",\"Pie\")'>Pie</option>
    <option id='Line' onClick='changechart(".$_GET['id'].",\"Line\")'>Line</option>
    <option id='Bar' onClick='changechart(".$_GET['id'].",\"Bar\")'>Bar</option>
    <option id='Odometer' onClick='changechart(".$_GET['id'].",\"Odometer\")'>Odometer</option>
    <option id='Radar' onClick='changechart(".$_GET['id'].",\"Radar\")'>Radar</option>
</select>

当我使用 mozilla firefox 浏览器时,这是正确的。但是当我使用 google chrome 浏览器时,onclick 事件(changechart 函数)不会执行。我该如何解决?谢谢 这是我渲染的 html 代码的一部分:

<select id='defchtype' class='selectpicker form-control' style='width:80%;'>
        <option id='Pie' onClick='changechart(126,"Pie")'>Pie</option>
        <option id='Line' onClick='changechart(126,"Line")'>Line</option>
        <option id='Bar' onClick='changechart(126,"Bar")'>Bar</option>
        <option id='Odometer' onClick='changechart(126,"Odometer")'>Odometer</option>
        <option id='Radar' onClick='changechart(126,"Radar")'>Radar</option>
</select>

这是我的 javascript 函数:

function changechart(id,chtype){
    var xmlhttp;
    if (window.XMLHttpRequest)
      {
          xmlhttp=new XMLHttpRequest();
      }
      else
      {
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
      xmlhttp.onreadystatechange=function()
      {
          if (xmlhttp.readyState==4 && xmlhttp.status==200)
          {
              //response="server/img/useravatars/"+xmlhttp.responseText;
              response=xmlhttp.responseText;


            document.getElementById("chartcontainer").innerHTML=response;
              document.getElementById(chtype).selected="true";

          }
    }
    var req="showchart.php?id="+id+"&chtype="+chtype;
    xmlhttp.open("GET",req,true);
    xmlhttp.send(); 
}

javascript 函数甚至不能在 chrome 中执行。但在 Firefox 中工作正常

【问题讨论】:

  • 你能把剩下的changeChart代码贴出来吗?
  • 您需要发布一个完整的代码示例,在这种情况下包括 JavaScript 和呈现的 HTML(不是 PHP)。
  • 您应该使用选择的 onchange 事件,而不是选项的 onclick。见*.com/questions/9972280/…

标签: javascript html google-chrome firefox


【解决方案1】:

您不应在option 元素中使用onClick 事件。改用 select 的 onchange 事件,正如在这个问题中已经讨论过的那样:javascript onclick alert not working in chrome

【讨论】: