JQuery trigger ("click") not working

Can someone explain what is wrong with the embedded code. It shows a warning about freezing, but does not execute the click event, as I expect, and the click does not work with either the tag <a>or the tag <select>. My goal is to expand the item selecton hover by triggering a click event

<!DOCTYPE html>
<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>

<body>
    <a id="linkElement" href="www.google.co.uk">click</a>

    <select name="cars" id="selectElemet">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="fiat">Fiat</option>
      <option value="audi">Audi</option>
    </select>


    <script>
        $(document).ready(function () {
            $("#selectElement").mouseover(function () {
                $("#selectElement").trigger("click");
            });

            $("#linkElement").mouseover(function () {
                alert('here');
                $("#linkElement").trigger("click");
            });
        });
    </script>
</body>

</html>
+4
source share
5 answers

.trigger("click")doesn’t actually click the element, it only activates the click handler attached to the element. Since you are not connected, no one starts.

You can use native .click()

$("#selectElement").get(0).click(); //get(0) returns reference to DOM element
+3
source

. 'selectElemet' 'selectElement'. , .

+2

trigger ('click') , 'click' , 'click'. , ('click') '', 'click'

+2

,

$('#selectElement').on('change', function() {
});
+1

. .

.

, .

$(document).ready(function() {
  $("#linkElement").mouseover(function() {
    $("#linkElement").trigger("click");
  });
  $("#linkElement").click(function(){
    window.location.href=$("#linkElement").attr("href");
  });
});
<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>

<body>
  <a id="linkElement" href="www.google.co.uk">click</a>

  <select name="cars" id="selectElemet">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="fiat">Fiat</option>
  <option value="audi">Audi</option>
</select>
</body>

</html>
Hide result
+1

Source: https://habr.com/ru/post/1673672/


All Articles