在JQuery中创建一组函数

时间:2013-05-01 18:57:13

标签: jquery html function

所以我试图更好地理解JQuery及其对Web内容和Web应用程序的使用,所以请听听我的意见。此测试页面的目标是能够使用按钮来更改,创建和删除内容。另一个目标是测试使用“输入”键从文本框中单击其中一个按钮的功能(模拟用户输入键以单击提交按钮)。这是我开发的代码,我对如何修复“destroyContent”的错误没有定义我有点困惑。显然我的语法已关闭,但我不确定如何修复它。任何人都可以协助并指出一些有用的参考资料吗?

JQuery:

$(document).ready(function () {
    $('#Scan').keypress(keyHandler);
});
$.keyHandler = function (e) {
    if (e.which == 13) {
        $(this).blur();
        $('#destroy').focus().click()
    }
}
$.changeHeading1 = function () {
    x = document.getElementById("Heading1")
    x.innerHTML = "It has changed";
}
$.createContent = function () {
    var para = document.createElement("p");
    var node = document.createTextNode("This is new");
    para.appendChild(node);

    var element = document.getElementById("div1");
    element.appendChild(para);
}
$.destroyContent = function () {
    var child = document.getElementById("p1");
    child.parentNode.removeChild(child);
}

(我保证在我的实际代码中看起来好多了,我在这里很难格式化)

对于HTML:

<h1 id="Heading1" />
<p id="p1" />
<button type="text" id="Scan" />
<button type="button" onclick="changeHeading1()" />
<button type="button" onclick="createContent()" />
<button type="button" id="destroy" onclick="destroyContent()" />

2 个答案:

答案 0 :(得分:2)

您正在创建destroyContent作为$的成员,但不是那样称呼它:

$.destroyContent = function () {onclick="destroyContent()"

您应该在destroyContent之外定义$或使用$来调用它。其中之一:

function destroyContent() {
    var child = document.getElementById("p1");
    child.parentNode.removeChild(child);
}

<button type="button" id="destroy" onclick="$.destroyContent()">

答案 1 :(得分:2)

第一件可能有用的事情是$只是全局命名空间的一个变量 - 在本例中是window。如果你转到chrome控制台,你会看到window.$。没什么特别的。还有window.jQuerywindow.$相同。

因此,当您访问函数时,它将尝试获取当前范围中的变量。所以当你这样做时:

<button type="button" id="destroy" onclick="destroyContent()" />

window.destroyContent()相同。如果要访问作为$变量属性的版本。所以你可以改变它们之一:

onclick="$.destroyContent()"
onclick="window.$.destroyContent()"

但是既然你想更好地理解jQuery,我会避免在标记中添加处理程序(正如大多数人会建议的那样)。而是通过jQuery创建处理程序,例如:

$('#destroy').click(function() {
  var child = document.getElementById("p1");
  child.parentNode.removeChild(child);
});

阅读jQuery事件API将有助于更好地理解如何执行此操作。他们有很好的例子:))