簡體   English   中英

動態添加元素屬性

[英]dynamically add elements attributes

我正在創建帶有手風琴內容內的表格的動態手風琴元素。 我需要通過傳遞給函數的變量動態設置文本。

我的代碼:

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

對於實例,我需要使用調用函數時收到的freq變量的文本值設置元素頻率。 另一個問題是使用傳遞給函數的標記字符串動態設置主div ID。 當HTML代碼是javascript變量時,該如何設置?

您可以連接字符串以設置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)

您能用下面的代碼替換您的函數以獲得預期的輸出嗎

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM