jquery assign and call ID with variable [closed]

断了今生、忘了曾经 提交于 2019-12-23 17:40:30

问题


let's say i have this code below:

 textInput = $('#outputTextInput').val();

   $('#outputAdd').click(function(){

       $('#status_table tr:last').after('<tr id="output_newrow_"+textInput><td>1</td><td id="type_row_"+textInput>lala</td><td id="num_row_"+textInput>num row '+textInput+'</td><td><img class="image" src="static/OffLamp-icon.png" style="height:64px; width=64px"/></td></tr>');

    });
   $('#outputRemove').click(function(){

        $('#status_table').find("#output_newrow_"+textInput).remove();


   });

Then i would like to call that selector with ID "output_newrow_"+textInput or "type_row_"+textInput such that...

$('#how_should_i_write_it_here').append(textInput)

I have no idea how i should call that selector...

Thanks in advance for all the help :)

Update! Here is the Fiddle link. My problem now is, i can't display the variable "textInput" and the index number is messy when i add and remove for a few times. For example, i key in "1,2,3" it will show index 2,3,4 on the table. but when i type in 3 and click remove, it removes index 2 (which is suppose to link to 1) instead.


回答1:


String concatenations in your code are wrong, also in your code index is undefined.

$('#outputAdd').click(function(){
   var textInput = $('#outputTextInput').val();
   var str = '<tr id="output_newrow_' +textInput + '">'
               + '<td>1</td><td id="type_row_' + textInput '">lala</td>'
               + '<td id="num_row_' + textInput + '">num row ' + textInput + '</td>'
               + '<td><img class="image" src="static/OffLamp-icon.png" style="height:64px; width=64px"/></td>'
          +  '</tr>';
   $('#status_table tr:last').after(str);

});
$('#outputRemove').click(function(){
    $("#output_newrow_"+textInput).remove();
});



回答2:


Your string concatenation was wrong

$('#outputAdd').click(function(){
    var textInput = $('#outputTextInput').val();

    $('#status_table tr:last').after('<tr id="output_newrow_'+textInput+'"><td>1</td><td id="type_row_"+textInput>lala</td><td id="num_row_"+textInput>num row '+index+'</td><td><img class="image" src="static/OffLamp-icon.png" style="height:64px; width=64px"/></td></tr>');

});
$('#outputRemove').click(function(){
    $('#status_table').find("#output_newrow_"+textInput).remove();    
});



回答3:


Pretty much the same way you are assigning it. Like this:

$("#output_newrow_" + textInput).appen(textInput);


来源:https://stackoverflow.com/questions/16139196/jquery-assign-and-call-id-with-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!