Javascript jQuery将元素添加到父级

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11248857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:08:16  来源:igfitidea点击:

jQuery adding elements to parent

javascriptjqueryhtml

提问by Sinmok

I'm having some trouble figuring out how to add elements to a parent object on a click event.

我在弄清楚如何在单击事件中将元素添加到父对象时遇到了一些麻烦。

The result that i'm hoping to achieve is this:

我希望达到的结果是:

<ul>
        <li><button>B1</button>
            <ul class="newul">
                <li><button>B1.1</button>
                    <ul class="newul">
                        <li><button>1.1.1</button></li>
                        <li><button>1.1.2</button></li>
                    </ul>
                </li>
                <li><button>B1.1</button></li>
            </ul>
        </li>
        <li><button>B2</button></li>
        <li><button>B3</button></li>
</ul>

Let's say I click button B2. I want a new UL added to the parent LI of that button and then be able to add new LI elements to the newly created UL. I hope that makes sense!

假设我单击按钮 B2。我想要一个新的 UL 添加到该按钮的父 LI,然后能够将新的 LI 元素添加到新创建的 UL。我希望这是有道理的!

So basically, click button, add new UL with class "newul" to the LI you're currently in -> add new LI's to that newly created UL.

所以基本上,单击按钮,将类为“newul”的新 UL 添加到您当前所在的 LI -> 将新 LI 添加到新创建的 UL。

The jquery I'm currently using is as follows:

我目前使用的jquery如下:

$('button').click(function(){
    //Get parent..
        var parent = $(this).parent();
        //Add a new UL to the parent and save it as newul           
        var newul = parent.add("ul");
                    //Add the class to the new UL
        newul.addClass('newul');               
        //Add a new li to the new UL            
            newli = newul.add('li');
            //Add a button to the new LI
            newli.append('<button></button>');

});

Unfortunately, this is having completely undesired effects and sticks buttons everywhere all over the place. I'd appreciate any help you can offer.

不幸的是,这会产生完全不受欢迎的效果,并且到处都是按钮。如果您能提供任何帮助,我将不胜感激。

Here's a visible example of what i'm after. The top part is the effect id like to achieve.

这是我所追求的一个明显的例子。顶部是想要实现的效果 id。

Example of desired result

所需结果示例

回答by merv

Even though @am not i am has the correct code. There is no explanation of why your code fails, and I think that's the answer you are asking for.

即使@am not 我也有正确的代码。没有解释为什么您的代码失败,我认为这就是您要的答案。

There are several problems in your code:

您的代码中有几个问题:

First

第一的

//Add a new UL to the parent and save it as newul           
var newul = parent.add("ul");

The 'ul'is a selector and so is going to search the DOM for other <ul>elements, rather than create a new one. Also, parent.add()method is returning the parentobject, not the ul's that you selected.

'ul'是一个选择器,因此将在 DOM 中搜索其他<ul>元素,而不是创建一个新元素。此外,parent.add()方法正在返回parent对象,而不是您选择的 ul。

Correct code:

正确代码:

//Add a new UL to the parent and save it as newul           
var newul = $("<ul>").appendTo(parent);

Second:

第二:

//Add a new li to the new UL            
newli = newul.add('li');

Same problem again, and since newulis actually still the parentyou're getting all types of craziness. Also, you're missing a var, but maybe I just don't get your closure.

同样的问题,因为newul实际上仍然是parent你得到所有类型的疯狂。另外,您缺少一个var,但也许我只是不了解您的关闭。

Correct code:

正确代码:

//Add a new li to the new UL         
var newli = $("<li>").appendTo(newul);

That's all. If you fix that in your code, it'll work.

就这样。如果您在代码中修复它,它将起作用。

However, unless you really need those references to persist, better performance is usually achieved if you pass the whole thing as a string:

但是,除非您确实需要保留这些引用,否则如果您将整个内容作为字符串传递,通常可以获得更好的性能:

$('button').click( function() {

  $(this).parent()
    .append(
      $('<ul class="newul"><li><button></li></ul>')
    );
});

Edit

编辑

And if you wanted all the new buttons to have the same functionality, use the on()methodand a class for your buttons:

如果您希望所有新按钮都具有相同的功能,请为您的按钮使用该on()方法和一个类:

$('body').on('click', 'button.ul-appending', function() {

  $(this).parent()
    .append(
      $('<ul class="newul"><li><button class="ul-appending"></li></ul>')
    );
});

You could change the 'body'selector to something much more specific so this doesn't get queried on every click on your page. Just make sure to add the class ul-appendingto all the existing buttons that aren't generated by this handler.

您可以将'body'选择器更改为更具体的内容,这样就不会在每次点击页面时都进行查询。只需确保将类添加ul-appending到所有不是由此处理程序生成的现有按钮。

JSFiddle

JSFiddle

回答by John Kalberer

One issue I see here is that the new buttons created will not have the click event bound to them. I fix this by using onand setting the event as a delegate. In doing so I give the outer ulan idof container. I also check to make sure you haven't already added a ulelement and append one if it isn't inside the li. Here is a working example.

我在这里看到的一个问题是,创建的新按钮不会绑定 click 事件。我通过使用on和设置事件作为委托来解决这个问题。在这方面,我给外ulidcontainer。我还检查以确保您尚未添加ul元素,如果它不在li. 这是一个工作示例

$('#container').on("click", "button.newbtn", function(){
    var parent = $(this).closest('li');
    var childUl = parent.children('ul');
    if(childUl.length === 0) {
        parent.append("<ul class='newul'></ul>");
        childUl = parent.children('ul');       
    }
    childUl.append($("<li><button class='newbtn'>" + $(this).html() + "." + (childUl.children().length + 1) + "</button></li>"));
});?

回答by thecodeparadox

$('button').click(function(){
         //Get parent..
        var parent = $(this).parent();

        //Add a new UL to the parent and save it as newul           
        var newul = $("<ul/>");

        //Add the class to the new UL
        newul.addClass('newul');               

        //Add a new li to the new UL            
        var newli = $('<li/>');

        //Add a button to the new LI
        newli.append('<button></button>');

        // add ul to parent li
        parent.append( newul.append( newli ) );

});

回答by Nathan

The issue here is that you're using .add()instead of .after().

这里的问题是您使用的是.add()而不是.after ()

.add()adds the passed element to the current selection. .after()adds the passed elements after the current selection.

.add()将传递的元素添加到当前选择。.after()在当前选择之后添加传递的元素。

Using .after(), we can simplify your script into a nice little one-liner:

使用.after(),我们可以将您的脚本简化为一个漂亮的小单行:

$('button').click(function(){
    $(this).after('<ul class="newul"><li><button></button></li></ul>');
});?

Since .after()inserts content next to the current element, there's no need to get the .parent(). .after()can take a complete string of HTML, so there's no need to use jQuery to manipulate the class and add the child elements.

由于.after()在当前元素旁边插入内容,因此无需获取.parent(). .after()可以采用完整的 HTML 字符串,因此无需使用 jQuery 来操作类和添加子元素。

Example.

例子。

回答by Nishu Tayal

Use .onfunction for dynamically added elements.

对动态添加的元素使用.on函数。

You can use something like this.

你可以使用这样的东西。

$(document).ready(function(){
    i = 1;
    $('body').on("click","button",function(event){
        $(this).after('<ul class="newul"><li><button>TestButton'+i+'</button></li></ul>');
        i++;
    });
});

Here is the DEMO. Adjust button with your css and button values accordingly.

这是演示。使用您的 css 和按钮值相应地调整按钮。

?

?