如何在以编程方式创建的jquery按钮上设置图标

时间:2012-10-26 15:05:04

标签: jquery button dynamic

您好我正在尝试动态创建按钮而无法获取按钮上的图标。我无法获得显示图标的按钮。我将不胜感激任何帮助。如何在removeBtn按钮小部件上设置关闭图标。

var a = [{
"_id": {
    "$oid": "50894875744e80aa5fa59853"
},
"name": "Test 1",
"color": "#b63e3e",
"propertyNames": ["Notes"]},
{
"_id": {
    "$oid": "50894afe744e80aa5fa59854"
},
"name": "Test 2",
"color": "#413bb6",
"propertyNames": ["Notes"]},
{
"_id": {
    "$oid": "50894c23744e80aa5fa59855"
},
"name": "Test 3",
"color": "#95eba5",
"propertyNames": ["Notes"]}];

for (var i = 0; i < a.length; i++) {

  var button = document.createElement('span');
  button.className = 'color-button';
  button.style.backgroundColor = a[i].color;

  var selectionItem = document.createElement('li');
  selectionItem.id = a[i]._id.$oid;
  selectionItem.className = "ui-widget-content";
  selectionItem.appendChild(button);

  selectionItem.appendChild(document.createTextNode(a[i].name));
  $('#id1').append(selectionItem);

  var removeBtn = $('<button/>',
            {
                    click: function(){
                    alert(this.parentNode.id);
                }
            });
  removeBtn.css("float","right");
  $("#"+a[i]._id.$oid).append(removeBtn);
}​

这是代码的jsFiddle链接: http://jsfiddle.net/vivsriva/VmEeR/5/

3 个答案:

答案 0 :(得分:1)

一种方法是为每个按钮添加具有背景图像的特定class

removeBtn.addClass('btn1');

和CSS一样:

button.btn1 { 
   background-image: url('yourimage')
}

答案 1 :(得分:1)

只是一个帮助你的指针。这是包含更多jQuery的代码,并在关闭按钮上包含jQueryUI的Close图标:

for (var i = 0; i < a.length; i++) {
    var button = $("<span />").addClass("color-button").css({ "background-color": a[i].color }),
        selectionItem = $("<li />").prop({ id: a[i]._id.$oid }).addClass("ui-widget-content").css({ "background-color": a[i].color }).text(a[i].name).prepend(button);

    $('#id1').append(selectionItem);

    var removeBtn = $("<button />").css({ "float": "right", "margin-top": ".1em", "width": "1em" }).appendTo($("#"+a[i]._id.$oid));

    removeBtn.button({ icons: { primary: 'ui-icon-circle-close' }, text: false })
    .click(function(e) {
        alert(this.parentNode.id);
    });
}

答案 2 :(得分:0)

就这样做

removeBtn.addClass('button-image').css("float","right");

.button-image 
{ 
   background-image: url('imageurl')
}
相关问题