2016-05-31 102 views
0

我正在用手风琴内容中的表创建动态手风琴元素。我需要通过传递给函数的变量动态设置文本。动态添加元素属性

我的代码:

function addAcc(marking, freq) { 
    var newID = marking; 

    var newTable = '<div id="startID"> \ 
        <h3>\ 
        </h3> \ 
        <table class="tg" style="width: 100%; height: 100%;padding: 0 0 0 0; margin: 0 0 0 0;background-color: #A0A6AB"> \ 
        <tr> \ 
        <th id="frequency"></th> \ 
        <th></th> \ 
        <th></th> \ 
        <th></th> \ 
        </tr> \ 
        </table> \ 
        </div>'; 

    $('.emitters').append(newTable) 
    $('.emitters').accordion("refresh"); 
    $('#startID').attr('id',newID); 
} 

为例我需要设置该元件用频率时调用该函数时接收到的频率可变的文本值。还有一个问题是使用传递给该函数的标记字符串动态设置主div ID。 当HTML代码是一个JavaScript变量时,如何设置它们?

回答

1

可以请你在下面的代码替换您的函数来获得期望的输出

function addAcc(marking, freq) { 
var newID = marking; 

var newTable = '<div id="'+marking+'"> \ 
       <h3>\ 
       </h3> \ 
       <table class="tg" style="width: 100%; height: 100%;padding: 0 0 0 0; margin: 0 0 0 0;background-color: #A0A6AB"> \ 
       <caption>'+freq+'</caption>\ 
       <tr> \ 
       <th id="frequency"></th> \ 
       <th></th> \ 
       <th></th> \ 
       <th></th> \ 
       </tr> \ 
       </table> \ 
       </div>'; 

$('.emitters').append(newTable) 
$('.emitters').accordion("refresh"); 
$('#startID').attr('id',newID); 

}

1

您可以连接字符串来设置HTML代码的变量。例如:

var newTable = '<div id="startID"> \ 
      <h3>\ 
      </h3> \ 
      <table class="tg" style="width: 100%; height: 100%;padding: 0 0 0 0; margin: 0 0 0 0;background-color: #A0A6AB"> \ 
      <tr> \ 
      <th id='; 

var frequency = freq; 

var newTable2 = '></th> \ 
      <th></th> \ 
      <th></th> \ 
      <th></th> \ 
      </tr> \ 
      </table> \ 
      </div>'; 

然后:

$('.emitters').append(newTable + frequency + newTable2) 
+2

就像一个魅力。非常感谢。 – ksup

+0

@kedar答案比我的方式更优雅(我在这里睡觉)... –

+1

@ksup接受正确的答案是什么? – Legionar