简体   繁体   English

JQuery:如何单击删除按钮,然后单击要删除的项目

[英]JQuery : how to click delete button then click on item to remove

Currently I'm using JQuery to spawn items into a HTML canvas to drag around and create visio style kind of drawings.目前我正在使用 JQuery 将项目生成到 HTML 画布中以拖动并创建 visio 样式的绘图。 The problem I'm having trouble figuring out is how to remove these items.我无法弄清楚的问题是如何删除这些项目。 Now I know I can use the .remove or the .click but the functionality I want is like this:现在我知道我可以使用 .remove 或 .click 但我想要的功能是这样的:

I want the user to click on the delete button then click on the item on the canvas they wish to remove that they created earlier.我希望用户单击删除按钮,然后单击他们希望删除之前创建的画布上的项目。 I'm not sure how to track the fact that the delete button has been clicked so when they click on the item they want to remove it can send the .remove to remove it from the canvas.我不确定如何跟踪删除按钮已被单击的事实,因此当他们单击要删除的项目时,可以发送 .remove 以将其从画布中删除。

I have seen lots of examples of a delete button next to a table or element so you can remove it once the button is clicked but I want a global delete button at the button of the screen that can be clicked then the user can click on the item anywhere on the canvas to be removed.我已经看到了很多表格或元素旁边的删除按钮的例子,所以你可以在点击按钮后将其删除,但我想要一个可以点击的屏幕按钮上的全局删除按钮,然后用户可以点击要删除画布上任何位置的项目。

Any help would be greatly appreciated.任何帮助将不胜感激。

Basically you want to set a flag whenever the delete button is highlighted and look at that flag whenever the user clicks the element.基本上,您想在删除按钮突出显示时设置一个标志,并在用户单击元素时查看该标志。

Here I am setting a class on the button.在这里,我在按钮上设置了一个类。 If the button has the specified class then the element should be deleted -如果按钮具有指定的类,则应删除该元素 -

 $(document).ready(function() { $("#delete").click(function() { $(this).toggleClass("deleting"); }); $("div").click(function() { if ($("#delete").hasClass("deleting")) $(this).remove(); }); });
 button.deleting { background-color: red; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div>Text1</div> <div>Test2</div> <div>Test3</div> <button id="delete">Delete</button>

You could assign a class to each of the elements that the user can remove.您可以为用户可以删除的每个元素分配一个类。

<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=IMG1&w=100&h=100" class="elements" />

Upon selecting(clicking) on the element remove the active class from all of the existing elements and assign the active class to the current item.选择(单击)元素后,从所有现有元素中删除活动类并将活动类分配给当前项目。

$('.elements').click(function () {
    $('.elements.active').removeClass('active');
    $(this).addClass('active');
});

Then upon delete button click.然后点击删除按钮。 Remove the element with the active class.删除具有活动类的元素。

$('#deleteElement').click(function () {
    $('.elements.active').remove();
})

Example here:这里的例子:

http://jsfiddle.net/SeanWessell/4emomnqe/ http://jsfiddle.net/SeanWessell/4emomnqe/

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

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