Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
848 views
in Technique[技术] by (71.8m points)

javascript - JQuery Click event not being triggered in Safari?

I'm trying to do something when a user selects an option from a select box - As simple as can be right? I'm using JQuery 1.3.1 to register a click handler with the id of the select box. Everything was fine until I tested using Chrome and Safari and found it didn't work.

  1. Firefox 3.05 - YES
  2. I.E 7.0.5730.13 - YES
  3. IE6Eolas - YES
  4. Sarafi 3.2.1 - NO
  5. Chrome 1.0.154.43 - NO

See below code:

<html>
<head>
    <script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
    <script language="javascript">
    $(document).ready(function(){
        $('#myoption').click(function() { alert('Select Dropdown was clicked: '+ $('#myoption').val()); });
    });     
    </script>
</head>
<body>
    <select id="myoption">
    <option value="A">A</option>
    <option value="B">B</option>
    </select>
</body>
</html>

Anyone know what I should be doing for this to work? The alert does eventually get triggered but only after double-clicking the select box?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I found my problem. For Select boxes, you need to register a handler for a "change" event rather than a "click" event. It's strange that Firefox and IE work with the click event.

To sum up, the following code works across all browsers:

<html>
<head>
    <script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
    <script language="javascript">
    $(document).ready(function(){
        $('#myoption').change(function() { alert('Select Dropdown was clicked: '+ $('#myoption').val()); });
    });         
    </script>
</head>
<body>
    <select id="myoption">
    <option value="A">A</option>
    <option value="B">B</option>
    </select>
</body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...