【问题标题】:.click handler in Chrome vs FirefoxChrome 与 Firefox 中的 .click 处理程序
【发布时间】:2014-11-30 11:58:16
【问题描述】:

问题:
为什么选择下拉菜单的 jquery .click 事件处理程序在 IE 和 Firefox 中可以正常工作,但在 Chrome 中不行?

详情:
我无法使用 Chrome 激活 .click 事件处理程序,但它适用于 IE 和 Firefox。在 IE 和 Firefox 中,当在下拉列表中选择“opt1”时,会显示一个警告框。在 Chrome 中,alert("Hello"); 语句甚至从未被解析过。我正在运行Win7。我浏览了JQuery API documentation,但没有运气。代码如下:

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="jquery-2.1.1.min.js"></script>
    <script src="ChromeTest.js"></script>    
</head>
<body>
    <select>
        <optgroup label="Some">
            <option id="opt1">1</option>
            <option id="opt2">2</option>
        </optgroup>
    </select>
    <input type="text" id="inputTest1" />
</body>
</html>

...有以下js支持:

// JavaScript source code
$(document).ready(function () {
    var showArea = $("#inputTest1");
    $('#opt1').click(function () {
        alert("Hello");
    });
});

【问题讨论】:

  • 您不只是在 select 上收听“更改”事件是否有特殊原因?
  • 改用 Chrome 的 Console.log("Hello"); 并使用页面检查器查看是否有任何输出。只是为了排除警报被屏蔽的可能性。
  • @skibulk Console.log 验证 .click 事件未被激活。
  • @TiesonT。我正在尝试将特定功能附加到下拉列表中的每个选项,这些功能在单击该选项时被激活。

标签: javascript jquery html


【解决方案1】:

这是 2009 年在 StackOverflow here 上提出的。

考虑到click 事件不考虑使用键盘进行的选择,并考虑在&lt;select&gt; 标记上使用change 事件,因为您可以检索相同的信息。

JSFiddle

$(document).ready(function () {
    $('select').on('change', function () {
        // If you need access to the element that was selected, use find
        console.log($(this).find('option:selected:first').text());

        // If you just need the value
        console.log($(this).val());
    });
});

【讨论】:

  • 感谢您的回复。但是,仍然存在错误,这在对 2009 年原始问题的回答中指出。如果已选择选项,并且用户单击已选择的选项,则未注册。
  • 如果您不关心键盘事件,请使用click 事件代替我提供的示例中的change 事件。即使用户根据需要单击已选择的选项,这也会激活。
【解决方案2】:

使用这个脚本

<script>
$(document).ready(function () {
$( "select" )
  .change(function () {
    var str = "";
    $( "select option:selected" ).each(function() {
      str += $( this ).text() + " ";
    });
    alert( str );
  })
  .change();

});
    </script>

你的 HTML

  <select>
        <optgroup label="Some">
            <option id="opt1">1</option>
            <option id="opt2">2</option>
        </optgroup>
    </select>

    <input type="text" id="inputTest1" />

【讨论】:

  • 感谢您的回复,但这与 szds 的答案基本相同……与我在该答案的评论中指出的问题相同。
【解决方案3】:

您可能为正在处理的特定页面禁用了警报。改用console.log 看看它是否记录任何内容

【讨论】:

  • 感谢您帮助缩小范围,但不幸的是,这并不适用。 Console.log 验证 .click 事件没有触发。
猜你喜欢
  • 1970-01-01
  • 2023-03-15
  • 2011-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-07
  • 1970-01-01
相关资源
最近更新 更多