动态添加元素属性

时间:2016-05-31 12:42:59

标签: javascript jquery html

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

我的代码:

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);
}

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

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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);

}

相关问题