When I get the j query value, it is output in undefined type.

Asked 2 years ago, Updated 2 years ago, 103 views

    head
        meta(charset='utf-8')
        script(src="//code.jquery.com/jquery-3.3.1.min.js")

        script.
            var a=$("#test_id").text();
            alert(a);

    body
        h1(id='test_id')='test value'

Why does it say undefined? I beg you.

javascript pug

2022-09-22 18:02

2 Answers

The above phenomenon occurs because the relevant elements were selected before all the DOM trees were completed.

Modify the script part as below or

$(function() {
  var a=$("#test_id").val();
  alert(a);
});

If you place the script block at the bottom of the body, it will work normally.

body
  h1(id='test_id')='test value'
  script.
    var a=$("#test_id").val();
    alert(a);


2022-09-22 18:02

Thank you. I'll do it as soon as I get off work.


2022-09-22 18:02

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.