我习惯了这样的javascript函数的语法:
function sample()
{
}
<input type="text" onclick="sampe()" />
一个简单的onclick甚至可以调用上面的javascript函数。我在互联网上找到了一个关于如何动态添加文本框的代码,现在我想制作我自己的版本但是为了让我首先需要理解它。我的左眼看不见了,所以这对我来说很难找到并阅读每一个指南。如果它不是太多,如果有人可以向我解释以下代码是如何工作的(FLOW)我会非常感激。我也不明白onclick事件只对添加按钮有效,但其他2个按钮仍然会调用该功能。
<html>
<head>
<title>jQuery add / remove textbox example</title>
<script type="text/javascript" src=" https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var counter = 2;
$("#addButton").click(function () {
if (counter > 10) {
alert("Only 10 textbox allowed");
return false;
}
$('<div/>',{'id':'TextBoxDiv' + counter}).html(
$('<label/>').html( 'Textbox #' + counter + ' : ' ))
.append( $('<input type="text">').attr({'id':'textbox' + counter,'name':'textbox' + counter}) )
.appendTo( '#TextBoxesGroup' );
counter++;
});
$("#removeButton").click(function () {
if (counter == 1) {
alert("No more textox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
for (i = 1; i < counter; i++) {
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
</script>
</head>
<body>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 : </label><input type='text' id='textbox1' name='textbox1' />
</div>
</div>
<input type='button' value='Add Button' id='addButton' onclick="dynamictext()"/>
<input type='button' value='Remove Button' id='removeButton' />
<input type='button' value='Get TextBox Value' id='getButtonValue' />
</body>
</html>
答案 0 :(得分:1)
以下是“内联”事件处理者:
onclick="dynamictext()"
在这种情况下,单击按钮时会调用名为dynamictext的函数。但是,由于您未定义dynamictext函数,因此抛出异常。如果您想查看例外,请打开Chrome并按ctrl + shift + J打开控制台,然后运行您的代码。单击该按钮时,控制台将显示“未捕获的ReferenceError:未定义dynamictext”。注意:内联事件处理程序通常被认为是不好的做法,因为它们不会将行为(应该在JavaScript中定义)与内容(可以在html中定义为静态内容或JavaScript定义为动态内容)分开。
请注意,您不必在html和JavaScript中分配onclick
处理程序。仅在您的html中或仅在您的JavaScript中分配处理程序就足够了。 (但是,如果在html中指定处理程序,则仍然必须定义您指定的函数(例如,在这种情况下为“动态文本”),而您在代码中未能执行此操作。
您提供的Javascript代码为您的三个按钮定义了onclick处理程序。在这里我展示其中一个:
$("#addButton").click(function () { // This anonymous function (function without a name),
if (counter > 10) { // is executed when the button with id="addButton"
alert("Only 10 textbox allowed"); // is clicked
return false;
}
$('<div/>', {
'id': 'TextBoxDiv' + counter
}).html(
$('<label/>').html('Textbox #' + counter + ' : '))
.append($('<input type="text">').attr({
'id': 'textbox' + counter,
'name': 'textbox' + counter
})) // It is safer to always use semicolons. You should put one here.
如果你仔细观察,你会注意到匿名函数作为参数传递给jQuery的“click”方法。 click方法添加了一个函数,该函数将在当前所选元素(即button#addButton
)的click事件被触发时执行(即,当有人点击该元素时)。