简体   繁体   English

onClick完全删除特定的DIV

[英]onClick completely remove a specific DIV

在此处输入图片说明

HTML page ..................................................................... HTML页面... .....................

   <form:form method="post" action="saveMiData.action" id="minorityForm"
                commandName="MinInterestModel">
                <div id="addMoreDiv">
                <label id="validNumber" style="display: none; color: #b94a48;"><spring:message
                                    code="Minority.validNumber" /><font color="#b94a48">*</font></label>
                    <div id="preacq" class="MICss">
                        <div id="linkopen">
                            <div class="span5">
                                <label class="abc" style="margin-bottom: 1px;"> <spring:message
                                        code="MinorityInterest.elementName" /></label>
                                <form:select id="glListName0" path="glElementId"
                                    name="glListName" class="input-block-level" size="1" multiple="bbn">
                                </form:select>
                            </div>

                            <div class="span5">
                                <label class="abc" style="margin-bottom: 1px;"> <spring:message
                                        code="MinorityInterest.AccountType" /></label>
                                <form:select path="accountType" id="accountName0"
                                    name="accountName" class="input-block-level" multiple="bbn">
                                    <option value="0">select</option>
                                    <option value="1">Debit</option>
                                    <option value="2">Credit</option>
                                </form:select>
                            </div>

                            <div class="span5">

                                <label class="abc" style="margin-bottom: 1px;"><spring:message
                                        code="MinorityInterest.preAcq" /></label> <input type="text"
                                    name="preAcqSurPlus" id="preacqas0" class="input-block-level abc"
                                    path="preAcqSurPlus"></input>
                            </div>

                            <div class="span5">
                                <label class="abc" style="margin-bottom: 1px;"> <spring:message
                                        code="MinorityInterest.Share" /></label> <input type="text"
                                    name="Shares" id="share0" path="Shares" class="input-block-level abc"></input>
                            </div>

                            <div class="span2" style="margin-top: 15px;">
                                            <div class="add_remove">
                                                <a><img onclick="addMore()"
                                                    src="<%=Config.getStaticURL()%>resources/img/Add-field.png" /></a>
                                            </div>
                                            <div class="add_remove">
                                                <a><img onclick="removeMI(this)" src= "<%=Config.getStaticURL()%>resources/img/remove-field.png" /></a>
                                            </div>
                                        </div>
                        </div>
                        <script type="text/javascript">
                            function addMore() {
                            //  alert("adddiv");
                                $("#preacq").clone().attr('id', 'preacq'+ cloneCount++).appendTo("#addMoreDiv");
                            }

                        </script>
    <script>

function removeMI(an){
//  alert($(this).attr('id'));
$(this).remove();
            alert("vaibhavremove"+an);

             //  alert($('#preacq0').attr('id','preacq0'+ cloneCount--).remove());

            if(cloneCount==1){
                  alert("No more textbox to remove");
                  return false;
               }   

        //  cloneCount--;
               $("#preacq" + cloneCount).remove();
}
</script>
                    </div>
                </div>
                <div class="span5" style="float: left;width:38%">
            <label class="abc" style="margin-bottom: 1px; margin-top:67px;  font-size: 17px; margin-left: 347px;"> <spring:message
                                        code="MinorityInterest.TotalAmount" /></label>
                </div>

                <div class="span5" style="float: right;">
                    <input type="text" style="margin-top: 67px;margin-left: -135px;width: 211px;">
                </div>
                <div class="span5" style="float: right;">
                    <input type="text" style="margin-top:67px;margin-left: -158px;width: 211px;">
                </div>
                <form:hidden path="parenCompanyId" id="PcId"/>
                <form:hidden path="childCompanyId" id="CcId"/>
                <form:hidden path="financialYearId" id="FyId"/>
                <form:hidden path="reportingPeriodId" id="rPId"/> 
                <div class="span6" style="float: right; margin-right: 0%">
                    <!-- <input id="saveMI" class="" type="button" value="Save" onclick="saveMI();"> -->
                    <button id="saveButtonId" name="save" value="save" onclick="saveMI();"
                        style="height: 30px; width: 50px;position: fixed; top: 627px;">save</button>
                </div>

            </form:form>
        </div>
My approach on removal function:

    function removeMI(){
        alert("vaibhavremove");
        //  alert($('#preacq0').attr('id','preacq0'+ cloneCount--).remove());
        if(cloneCount==1){
            alert("No more textbox to remove");
            return false;
        }   
        cloneCount--;
        $("#preacq0" + cloneCount).remove();
    }

It works fine but my requirement is when click on minus button, the selected div will be removed, not the last one, as I'm creating the div id dynamically. 它工作正常,但我的要求是,当单击减号按钮时,将删除所选的div,而不是最后一个,因为我正在动态创建div id

Code for creating div id : 用于创建div id代码:

<script type="text/javascript">
    function addMore() {
        //  alert("adddiv");
        $("#preacq0").clone().attr('id', 'preacq0'+ cloneCount++).appendTo("#addMoreDiv");                          
    }
</script>

Remove button markup: 删除按钮标记:

    <div class="add_remove"> 
        <a>
            <img onclick="removeMI()" src= "<%=Config.getStaticURL()%>resources/img/remove-field.png" />
        </a>
    </div>
</div>

Thanks in advance. 提前致谢。

// For deleting article row
$(document).on('click','.delete-article',function() {
    var selectedRowForDeletion = $(this).closest(".dynamic-new-row");
    selectedRowForDeletion.remove();
});

Where: 哪里:

.delete-article = class of the remove button/image .delete-article =删除按钮/图像的类

.dynamic-new-row = class of every row in div/tr to be removed .dynamic-new-row =要删除的div / tr中每一行的类

selectedRowForDeletion = object of the selected row to be removed selectedRowForDeletion =要删除的选定行的对象

Hope this helps. 希望这可以帮助。

It can be done. 可以办到。 The logic behind your script however is totally wrong. 但是,脚本背后的逻辑是完全错误的。

Let me explain: 让我解释:

  • What gonna happen if someone attempt to remove the main instance ( #preacq ) that has to be cloned? 如果有人尝试删除必须克隆的主实例#preacq ),将会发生什么?
  • What if someone want o clone the instance where the "clone" button is attached to (otherwise why to place "clone" button inside each instance but copy the main )? 如果有人想要克隆“克隆”按钮所在的实例 (否则为什么要在每个实例中放置“克隆”按钮但复制main )怎么办?
  • Dealing with id 's is overkill for that purposes. 出于这个目的,处理id是过分的。 The main instance include elements with their own id attributes (like: select id="glListName0" ). 主要实例包含具有其自己的id属性的元素(例如: select id="glListName0" )。 Therefore number of elements with the same id is increased each time you clone the main instance . 因此,每次克隆主实例时,具有相同id的元素数量都会增加。 Keep in mind that the id of each DOM element must be unique 请记住,每个DOM元素的id 必须唯一
  • Since each instance has "clone" and "remove" buttons, the clone instance should be attached right after the instance that has been cloned, not at the end of the list (otherwise - once again - why to place "clone" button inside each instance ?). 由于每个实例都有“ clone”和“ remove”按钮,因此克隆实例应在已克隆的实例 之后立即附加,而不是在列表的末尾(否则-再次-为什么将“ clone”按钮放在每个实例实例 ?)。
  • Clicking "delete" button in main instance , you're reducing cloneCount but not deleting any elements, since it has no number attached to its id attribute but has active "delete" button. 主实例中单击“删除”按钮,这是在减少cloneCount 而不删除任何元素,因为它的id属性没有附加数字,但具有活动的“删除”按钮。

The answer provided by @imsheth is somehow correct. @imsheth提供的答案某种程度上是正确的。 You should definitely avoid dealing with id 's when comes to .clone() and use scenario where you could operate on classes and use "parental" style selectors. 当涉及到.clone()时,您绝对应该避免处理id并使用可以对类进行操作并使用“父代”样式选择器的方案。 Otherwise, you have to care about each element id inside cloned instance. 否则,您必须关心克隆实例中的每个元素id


Why your script does not remove the instance you want? 为什么您的脚本没有删除所需的实例?

Each time you press "clone" button, the cloneCount value gets increased by 1 .: 每次按下“克隆”按钮, cloneCount值都会增加1

function addMore() {
    $("#preacq").clone().attr('id', 'preacq'+ cloneCount++).appendTo("#addMoreDiv");
    // say, you cloned instance 5 times, so the "cloneCount" value is now 5
}

When comes to delete, you're actually checking the latest value of cloneCount (which actually represents also the latest created element): 删除时,实际上是在检查cloneCount最新值(它实际上还代表最新创建的元素):

function removeMI(){
    // because you've created 5 elements, the current "cloneCount" value is 5:
    $("#preacq" + cloneCount).remove();
    // the above will delete "#preacq5" element, which is the latest created.
}

How to repair this? 该如何修复?

I won't focus on another issues there, since the actual question is how to remove a specific DIV based on id . 由于实际问题是如何基于id删除特定的DIV,因此我不会在此讨论其他问题。 So there's an example of a quick fix: 因此,有一个快速修复的示例:

function addMore(){
    var cloned = $("#preacq").clone().attr('id', 'preacq'+ cloneCount++);
    // add "data-parent-id" attribute to the "remove" button (to indicate which div should be deleted when this button is clicked):
    cloned.find('.add_remove a img').attr('data-parent-id', '#preacq'+ (cloneCount-1));
    cloned.appendTo("#addMoreDiv");
}

// pass the clicked button (btn) to the function:
function removeMI(btn){
    // get the element id from data attribute of the button:
    $($(btn).data('parent-id')).remove();
}

I'd however use @imsheth solution. 但是我会使用@imsheth解决方案。

It is hard to tell what you are doing here, but if you are dynamically creating the rows, than they are likely not getting the "delete" function assigned to the minus image you are adding to the dom after the page has loaded. 很难说出您在这里做什么,但是如果动态创建行,则在页面加载后,它们很可能没有获得分配给负图像的“删除”功能,而该负图像将添加到dom中。 If you pass the assignment through the body (or a parent container) than they will the minus sign will work even if it is added to the dom later. 如果您通过主体(或父容器)传递分配,则即使负号稍后添加到dom中,减号也会起作用。 Use this type of function assignment sparingly, I generally only do it this way in these types of situations. 谨慎使用这种类型的功能分配,我通常只在这种情况下才这样做。

$('#minorityForm').on('click', '.myMinusDiv', function(){ alert("minus was clicked") });

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

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