简体   繁体   English

将JavaScript变量作为值注入到匿名函数中

[英]Inject JavaScript variable as value in anonymous function

I have a form where I add inputs dynamically. 我有一个表单,可以动态添加输入。 When I add a new input I increment a global id variable and concatenate it to the input's id so it will be unique. 当我添加一个新输入时,我增加了一个全局id变量并将其连接到输入的id,因此它将是唯一的。 I also create a delete button for each input that should remove that input and himself (through removing the container <div> they are in). 我还为应该删除该输入和他本人的每个输入创建一个删除按钮(通过删除它们所在的容器<div> )。 I do the remove process by adding an anonymous function to the delete button's click event via JQuery: 我通过通过JQuery向删除按钮的click事件中添加匿名函数来执行删除过程:

$('#deletebutton' + id).click(function(){
    $('#inputcontainer' + id).remove();
});

The only problem with this solution that it isn't work in the way I excepted it. 这种解决方案的唯一问题是,它不能以我所独有的方式工作。 When I click any of the delete buttons it will delete the last input container because when I click, it executes the anonymous function and evaluate the id variable at that time, so the selected id will be the last input's id. 当我单击任何一个删除按钮时,它将删除最后一个输入容器,因为当我单击时,它会执行匿名函数并在那时评估id变量,因此所选的id将是最后一个输入的id。 So always the last input container will be deleted. 因此,总是最后一个输入容器将被删除。

Is there a way to rewrite this function so when I add it to the click event, than it will evaluate the id , inject it and handle the selection as if it had been written like #inputcontainer1 , #inputcontainer2 , etc. 有没有办法重写此函数,所以当我将其添加到click事件中时,它将评估id ,注入它并处理选择内容,就好像它是像#inputcontainer1#inputcontainer2等那样编写的。

I can make this by adding the function's body to the button's onclick() event: 我可以通过将函数的主体添加到按钮的onclick()事件中来实现:

var newbutton = '<button id="deletebutton' + id + '" type="button" onclick="javascript:$(\'#inputcontainer' + id + '\').remove();">x</button>';

But is there a way doing this with the JQuery click() way? 但是有没有办法使用JQuery click()方法呢?

To answer the specific question, you'd have to dig the id out of the DOM: 要回答特定问题,您必须从DOM中挖掘ID:

$('#deletebutton' + id).click(function(){
    var id = $(this).attr("id").replace('deletebutton','');
    $('#inputcontainer' + id).remove();
});

You could also store it as data when you create the delete button: 创建删除按钮时,也可以将其存储为数据:

<button data-id="1" id="deletebutton1">

$('#deletebutton' + id).click(function(){
    var id = $(this).data("id");
    $('#inputcontainer' + id).remove();
});

Note that in both of these cases, id is a string, not an integer. 请注意,在这两种情况下, id都是字符串,而不是整数。

When I click any of the delete buttons it will delete the last input container [...] 当我单击任何一个删除按钮时,它将删除最后一个输入容器 [...]

If your 1st snippet is inside a loop, id probably isn't being scoped to each iteration. 如果您的第一个代码段在循环中,则可能不是将id限制为每次迭代的范围。 So, by the time one of the click() events is triggered and it's trying to use .remove() , id will have already been set to the last value given while looping. 因此,在click()事件之一被触发并尝试使用.remove()id将已经设置为循环时给定的最后一个值。

You can use an IIFE to create an additional function scope for keeping a different id for each iteration (ref: closure ). 您可以使用IIFE创建额外的function范围,以便为每次迭代保留不同的id (参考: 闭包 )。

/* loop */ {
    var id = ...;

    (function (id) {
        $('#deletebutton' + id).click(function(){
            $('#inputcontainer' + id).remove();
        });
    })(id);
}

Though, for future reference, ECMAScript 6 is adding block scoping which should allow for: 但是,为了将来参考,ECMAScript 6添加了块作用域 ,这应允许:

/* loop */ {
    let id = ...;

    $('#deletebutton' + id).click(function(){
        $('#inputcontainer' + id).remove();
    });
}
$('#deletebutton' + id).click(function(){
    $(this).parent().remove();
});

If the container isn't a direct parent and doesn't have a class you could do: 如果容器不是直接父级并且没有类,则可以执行以下操作:

$('#deletebutton' + id).click(function(){
    var idNum = $(this).attr("id").replace('deletebutton','');
    $("#inputcontainer"+idNum).remove();
});

If you've got appropriate classes (or can add them), this would be best: 如果您有合适的类(或可以添加它们),则最好:

$(document).on("click",".deleteButton",function() {
    $(this).parents(".inputContainer").remove();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM