jQuery 检测 jQuery 本身添加的类

标签 jquery

我正在开发一个表单,需要使用+/-(加号、减号)按钮动态添加字段。

代码完美地添加了字段,但是当我尝试删除它时,它不起作用。

这是我的代码:

HTML

 <div class="jfs_product_detail_fields">
                    <span class="jfs_product_name"><input type="text" name="product name" placeholder="Product Name"></span>
                    <span class="jfs_product_id"><input type="text" name="product ID" placeholder="Product ID#"></span>
                    <span class="jfs_qty"><input type="text" name="Qty" placeholder="Quantity"></span>
                    <button class="jfs_btn">+</button>
                    <div class="jfs_clr"></div>
                </div>

JQUERY

// making them unique
var num = 1;

// cloning
jQuery('.jfs_btn').on('click', function () {
    if (jQuery(this).hasClass('jfs_remove')) {
        alert('test');
    } else {
        var fields = '<div id="jfs_product_detail_fields"><span class="jfs_product_name"><input type="text" name="product_name_' + num + '" placeholder="Product Name"></span><span class="jfs_product_id"><input type="text" name="product_id_' + num + '" placeholder="Product ID#"></span><span class="jfs_qty"><input type="text" name="qty_' + num + '" placeholder="Quantity"></span><button class="jfs_btn jfs_remove">-</button><div class="jfs_clr"></div></div>';
        num = num + 1;
        jQuery('.jfs_product_detail_fields:first').before(fields);
    }
});

这也是我在 JS Fiddle 上的代码:My Fiddle Link

任何帮助或提示将不胜感激:)

奥马尔

最佳答案

演示:https://jsfiddle.net/64sfpf5j/1/

删除按钮是动态创建的,因此您应该使用 .on() 方法,如下所示:

jQuery('body').on('click', '.jfs_remove', function () {

    $(this).closest('div').remove();
});

关于jQuery 检测 jQuery 本身添加的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29923579/

相关文章:

javascript - 在 Safari 中使用 jQuery 检测页面缩放变化

javascript - 动态将类设置为选定的 <li> 标记

javascript - 我的一些谷歌分析事件在 24 小时后没有反射(reflect)

jquery - Bootstrap 3 : How to make margins responsive?

JavaScript:循环遍历 DOM 树并替换文本?

javascript - 页面重新加载时更改文本

javascript - 添加淡入淡出到 jquery 图像替换

javascript - 如何在CKEditor的保存按钮上捕获点击事件

javascript - JQuery 在没有任何错误消息的情况下停止工作

javascript - 来自包含的 div 中的意外 jquery 事件行为