0

我有这个 Javascript/JQuery 代码:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

<script type="text/javascript">

    name = $("#name").val();

    alert("Name: " + name);

</script>

这个HTML:

<form name="report" action="send.php" method="post">

    <input type="text" name="name" id="name" value="Senna" />
    <input type="submit" value="Send" />

</form>

当页面加载时,我得到“名称:未定义”而不是“名称:塞纳”。

有人可以帮我得到预期的结果吗?

4

3 回答 3

2

You should place your code inside the DOM ready handler:

$(function() {
    var name = $("#name").val();
    alert("Name: " + name);
});

Otherwise you are trying the work with elements which are not yet loaded.

于 2012-07-03T21:55:58.327 回答
2

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code.

You need to indicate to execute the function once the page has been loaded. Currently you are only defining it and not decalring when to execute it.

$(document).ready(function(){
    name = $('#name').val();
    alert('Name: ' + name);
});

Or:

$(function(){
    name = $('#name').val();
    alert('Name: ' + name);
});
于 2012-07-03T21:57:29.703 回答
1

You need the document.ready callback.

Place your code inside a function like this -

$(function(){
  // code goes here
});

You need to use this callback to know when jQuery and the entire DOM is loaded. Only then can you start to manipulate the Markup and CSS with your jQuery code.


The code above is really just shorthand for this -

$(document).ready(function(){
  // code goes here
});

This uses the .ready() method - http://api.jquery.com/ready/
An extract from the description of the .ready() function -

... The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. ...

emphasis added

于 2012-07-03T21:56:28.210 回答