如何使用jQuery在选择HTML控件之外放置一个删除按钮图标

How to place a delete button icon besides select HTML control using jQuery?

本文关键字:一个 图标 按钮 删除 jQuery 何使用 选择 HTML 控件      更新时间:2023-09-26

我的jQuery代码如下:

    $(function () {
      $(document).delegate('.products','click',function (e) {
        var table_id = $(this).closest('table').attr('id');
        var no = table_id.match(/'d+/)[0];            
        var first_row = $('#'+table_id).find('tbody tr:first').attr('id');
        var new_select = $('#'+first_row).children('td:first').find('select:first').clone();
        var tbody = $('#' + table_id + ' tbody');
        var n =  $(this).closest('table').find('select.prod_list').length+1;
        new_select.attr('id','product_id_'+no+'_'+n);
        new_select.attr('name', 'product_id_'+no+'['+n+']');
        $('#'+table_id).find('tbody tr:first').children('td:first').append(new_select);
        $('<button style="color:#C00; opacity: 2;margin-top: 6px;" type="button" class="close delete" data-dismiss="alert" aria-hidden="true">&times;</button>').appendTo( $(new_select.find('select')) );//Here I'm having an issue in placing the delete icon button
    });
  });

您可以看到,我正试图将删除图标按钮附加到新添加的<select>,但我没有。有人能在这方面帮助我吗?js的小提琴是:http://jsfiddle.net/L247t/

您应该使用.insertAfter()而不是.appendTo()

$('<button style="color:#C00; opacity: 2;margin-top: 6px;" type="button" class="close delete" data-dismiss="alert" aria-hidden="true">&times;</button>').inertAfter( $(new_select.find('select')) );

您正在尝试在select字段中添加按钮。这不可能。在select字段中,你只能添加options。

你可以做两件事:

// Adding a delete button after the select-field
new_select.after('<button style="color:#C00; opacity: 2;margin-top: 6px;" type="button" class="close delete" data-dismiss="alert" aria-hidden="true">&times;</button>');

// Appending the select field with an delete option
new_select.append('<option value="del">&times;</option>');

我在这里更新了你的小提琴:http://jsfiddle.net/L247t/1/