2012-03-29 30 views
0

中添加Data-test-id屬性到​​我有TableTextareaButton。當Textarea內的用戶類型,然後點擊我的Button文本被添加到Table作爲行與下面的代碼:在我的Jquery

<script type="text/javascript"> 
$(function() { 
    $('#CustomButton').click(function() { 
     $('#CustomPickedTable tbody').append(
      $('<tr/>', 
      { 
      click: function() { 
        $(this).remove(); 
        }, 
       html: $('<td/>', { 
        text: $('#CustomQuestionText').val() 
       }) 
      }) 
     ); 
     return false; 
    }); 
}); 
</script> 

TextArea內的用戶類型,然後點擊該Button是我的Table Tbody得到這個<td>What user typed..</td>我想什麼是我的表得到<td data-test-id="5">what user typed..</td>.

是否有任何解決方案,在我的jQuery所以我<td>得到的數據測試-id屬性?

在此先感謝!

回答

1

你可以這樣來做

$('#CustomButton').click(function() { 
    $('#CustomPickedTable tbody').append(
     $('<tr/>', { 
      html: $("<td />", { 
       html: $("#CustomQuestionText").val(), 
       'data-attr-id': 5 

      }) 
     }) 
    ); 
    return false; 
}); 
+0

我不能'使用click:function(){ $(這)一個.remove(); – Obsivus 2012-03-29 08:39:12

+0

@RammtinAvar,查看我的更新 – Starx 2012-03-29 08:56:53

+0

+1 for fiddle ... – diEcho 2012-03-29 08:58:02

1

嘗試

{ 
       click : function() {$(this).remove();}, 
       html: $('<td/>', {text: $('#CustomQuestionText').val()}, 
       attr : { 'data-test-id' : 'whatever' } 
    } 

Reference

+0

我嘗試過,但在其不工作的一些奇怪的方式,你可以看看它和編輯我的jsfiddle http://jsfiddle.net/jmdy9/ – Obsivus 2012-03-29 08:34:55

+0

@RammtinAvar,該解決方案將'attr'定義爲不屬於'data-test-id'的屬性。檢查我的回答 – Starx 2012-03-29 08:37:44

+0

@RammtinAvar你給定的jsfiddle甚至沒有使用你的代碼。首先使這個完美 – diEcho 2012-03-29 08:57:03

0

聲明動態ID vairable並得到錶行的指望它,然後將它應用於TD元素ID

var dynamicId = document.getElementById("yourtable").getElementsByTagName("TR").length; 

html: $('<td data-test-id="' + dynamicId + '"/>', { 
       text: $('#CustomQuestionText').val() 
      })