为什么jQuery .insertAfter在此示例中不起作用? [英] Why does jQuery .insertAfter not work in this example?
本文介绍了为什么jQuery .insertAfter在此示例中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在下面的示例中,警报显示,但是 #message为空白.
In the following example, the alert shows, but the #message is blank.
如果我注释掉 .insertAfter行,则#message将正确显示.
If I comment out the .insertAfter line then the #message is displayed correctly.
.insertAfter为什么在此示例中不起作用?
Firebug刚好越过它.
Firebug just steps right over it.
javascript:
google.load("jquery", "1.3.2");
//run when page is loaded
google.setOnLoadCallback(function() {
$('.languageChooser select').bind('click', function() {
var numberOfItems = $('.languageChooser select option:selected').length;
$('#message').hide().html("You have selected " + numberOfItems + " " + smartPlural('language',numberOfItems) + ".").fadeIn('slow');
if(numberOfItems == 1) {
$('#message').insertAfter('<div>Use the CTRL and SHIFT keys to select multiple items.</div>');
alert('here');
}
});
function smartPlural(itemName, numberOfItems) {
if(numberOfItems == 1) {
return itemName;
} else {
return itemName + 's';
}
}
});
html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<title>Text XHTML Page</title>
<link href="css/main.css" rel="stylesheet" type="text/css" media="all"/>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="javascript/main.js"></script>
</head>
<body>
<div class="languageChooser">
<div class="title">Please choose a language:</div>
<select size="4" multiple="multiple">
<option>C#</option>
<option>Ruby</option>
<option>PHP</option>
<option>VB.NET</option>
<option>JavaScript</option>
<option>Scala</option>
</select>
<div id="message"></div>
</div>
</body>
</html>
推荐答案
insertAfter 仅适用于DOM中已经存在的元素,请看一下文档:
insertAfter works only with elements already existing on the DOM, give a look to the documentation:
元素必须已经插入 进入文档(您不能在 如果不在另一个元素中 页面).
The elements must already be inserted into the document (you can't insert an element after another if it's not in the page).