使用纯javascript删除元素

时间:2015-11-18 21:42:35

标签: javascript html

我试图删除ul(列表项)中的元素,只使用javascript。因为我动态生成html,所以我试图设置onclick,因为我在下面创建它。但是,当我尝试单击(请参阅小提琴)时,元素不会被删除。相关功能如下:

#include "XmlWriter.h"


class Campus
{
private:
    std::string city;
    std::string region;
    int capacity;
    std::list<Student> students;
    std::list<Teacher> teachers;

public:

    void persist(Archive* archive)
    {
        archive->value("city",city);
        archive->value("region",region);
        archive->value("capacity",capacity);

        archive->value("Students","Student",students);
        archive->value("Teachers","Teacher",teachers);
    }

}

class Student
{
private:
    int ID;
    std::string name;
    std::string surname;

public:

    void persist(Archive* archive)
    {
        archive->value("ID",ID);
        archive->value("surname",surname);
        archive->value("name",name);        
    }

}

class Teacher
{
protected:
    int ID;
    std::string name;
    std::string surname;
public:

    void persist(Archive* archive)
    {
        archive->value("ID",ID);
        archive->value("surname",surname);
        archive->value("name",name);
    }
};

Campus c;

XmlWriter writer;
writer.write("campus.xml","Campus",c);

https://jsfiddle.net/youngfreezy/7jLswj9b/5/

3 个答案:

答案 0 :(得分:5)

你的第一个问题是你的html中有“deleteEvent”,jsFiddle不喜欢它。

第二个问题是你在deleteEvent中使用了错误的元素,因此父级也是错误的。

请参阅更新的小提琴:https://jsfiddle.net/7jLswj9b/7/

var deferredAjaxCalls = jobsList.map(function(job) {
    return $.ajax({
        url: "/myurl",
        method: "POST",
        contentType: "application/json",
        dataType: "json",
        data: mydata
    }).then(process);// where `process` is a function that accepts $.ajax's (data, textStatus, jqXHR) and returns a *single* value/object - the result of the processing. This will standardise the data delivered below by $.when() to its success handler.
});
$.when.apply(null, deferredAjaxCalls).then(function() {
    // Due to `.then(process)` above, `arguments` are guaranteed to comprise one arg per ajax call.
    // Otherwise you potentially have the problem reported here - http://stackoverflow.com/questions/12050160/
    for (var k=0; k<arguments.length; k++) {
        // Combine the results of the individual results of the success part of all the ajax calls and execute some more code synchronously.
    }
    // In this function deliver an error by returning `$.Deferred().reject(new Error('myReason'))`
    return combined_result;
}, function(jqXHR, status, error) {
    // This hander will receive multiple $.ajax() params, which are best normalised into a single Error object. 
    return new Error(status); // similar to .then(process) above, reduce $.ajax's error args to a single "reason".
}).then(null, function(err) {
    // All errors delivered by code above arrive here as a js Error.
    // But please note that, in jQuery <v3.0, any uncaught errors above will genuinely throw (to the console).
    console.log(err.message);
});

答案 1 :(得分:1)

如果使用onclick属性将事件代码设置为字符串,this上下文将丢失。

注册事件处理程序的最佳方法是addEventListener

listItem.addEventListener("click", deleteEvent);

作为后备,请将您的事件代码设置为函数:

listItem.onclick = deleteEvent;

这是不鼓励的,因为你只能以这种方式为每个事件设置1个事件处理程序。

如果您确实 设置代码内联,请通过参数传递this的值:

<ul id="events" onclick="deleteEvent(this)">...</ul>

function deleteEvent(element) {
  // ...
}

答案 2 :(得分:1)

你的jsFiddle和你的代码有几个问题。

事件处理程序的范围

您正在使用inline event handler。内联事件处理程序在全局范围内执行。但是,因为默认情况下小提琴将JavaScript代码包装在函数中,deleteEvent 不是全局。控制台显示错误:

Uncaught TypeError: Cannot read property 'appendChild' of null

有三种方法可以解决这个问题:

事件处理程序中的

this

因为您将函数调用为deleteEvent()this不会引用触发事件的DOM元素。它将引用window,即全局对象,它没有parentNode属性。

如果您使用不同的方式来绑定处理程序,如上所述,那么该问题可能会自行解决。否则,您必须以deleteEvent引用该元素的方式调用this

onclick="deleteEvent.call(this)"

当然你也可以改变deleteEvent的定义来接受元素作为参数。

但是,在您的小提琴中,您实际上将事件处理程序附加到<ul>元素,而不是每个<li>元素。在这种情况下,您必须将事件对象传递给函数,并从中获取原始目标:

onclick="deleteEvent(event)"

var deleteEvent = function (event) {
  //Remove the parent list item from the ul
  event.target.parentNode.removeChild(event);
}

DEMO

错误的节点参考

您似乎正在删除deleteEvent中的错误节点。 listItem实际上是<ul>元素,因为它是被点击元素的父元素。因此,ul将成为<ul>元素的父级。

由于this已引用<li>元素,因此此处需要listItem,而ul应为this.parentNode。缩短形式:

var deleteEvent = function () {
  //Remove the parent list item from the ul
  this.parentNode.removeChild(this);
}

return false无效

return false通常用于阻止事件的默认操作。但是,单击li元素没有默认操作。此外,该值必须从事件处理程序返回。 deleteEvent不是您的事件处理程序,它由您的事件处理程序调用。因此,如果您想要返回其返回值,则必须完全按照以下方式执行:

listItem.setAttribute("onclick", "return deleteEvent()");

但同样,你应该更喜欢绑定事件处理程序。

节点创建无效

在您的问题的代码中,您试图在任意对象上调用setAttribute并尝试将任意对象附加到DOM元素。那不会奏效。您必须使用document.createElement来创建新元素:

var li = document.createElement('li');

看来你在小提琴中正确地做到了这一点。