0
我有一些JS/JQuery的问题。我正在使用一些脚本从<TH>
标记中的数据创建一个数组,然后对该数据进行一些格式化,以创建响应表的新内容和样式。从不同的表中TH数据创建单独的数组
<script>
$(document).ready(function() {
// Setup an array to collect the data from TH elements
var tableArray = [];
$("table th").each(function(index){
var $this = $(this);
tableArray[index] = $this.text();
});
console.log(tableArray);
alert(tableArray);
// Create class name based on th values and store as variable
var tableString = tableArray.join();
tableString = tableString.replace(/,/g, '_')
tableString = tableString.replace(/ /g, '-')
var tableClass = ".responsive-table."+tableString;
console.log(tableClass);
// Push tableClass variable into the table HTML element
var applyTableClass = tableClass;
applyTableClass = applyTableClass.replace(/\./gi, " ") //converts the style declaration into something i can insert into table tag (minus the dots!)
console.log(applyTableClass);
$("table").addClass(applyTableClass);
// Create a loop which will print out all the necessary css declarations (into a string variable) based on the amount of TH elements
var i = 0;
var styleTag = "";
while (tableArray[i]) {
styleTag += tableClass+" td:nth-of-type("+[i+1]+"):before { content: '"+tableArray[i]+"'; }";
i++;
}
// Push the styleTag variable into the HTML style tag
$('style#jquery-inserted-css').html(styleTag);
// Below is just a test script to check that values are being collected and printed properly (use for testing)
//$('#css_scope').html('<p>'+styleTag+'</p>');
});
</script>
如果页面内有单个表格,但不存在附加表格时,此功能非常有用。原因是创建数组的循环继续进行,并且不知道在一个表的末尾停止并返回,然后为下一个表创建一个新数组。我想象我需要建立一个循环来创建数组。
这是我辞职的地方,因为我的脚本技能有限。任何人都可以请建议一种方法让我的代码循环通过多个表,创建多个数组,然后创建单独的样式声明?
谢谢@Wery,这绝对是我的伎俩!这是我正在寻找的直接解决方案 - 特别是“追加”方法。 –