gpt4 book ai didi

javascript - 获取数据属性并追加优化

转载 作者:行者123 更新时间:2023-11-30 08:38:29 24 4
gpt4 key购买 nike

我一直在摆弄并使用我在这里找到的一些代码,我设法获得了一些工作代码,尽管我想知道它是否可以进一步优化。

我尝试对代码进行注释,以便展示我的思考过程。如果有人知道实现 [获取 data-tid 属性并将该值附加到该表行中的跨度到 td] 的更好方法,我很想听听。

<table>
<tr data-tid="3"><td class="col_f_icon">aaa</td><td class="col_f_content">fdsfdsf</td></tr>
<tr data-tid="2"><td class="col_f_icon">aaa</td><td class="col_f_content">fdsfdsf</td></tr>
<tr data-tid="5"><td class="col_f_icon">aaa</td><td class="col_f_content">fdsfdsf</td></tr>
<tr data-tid="6"><td class="col_f_icon">aaa</td><td class="col_f_content">fdsfdsf</td></tr>
</table>

$j = jQuery.noConflict();
$j(document).ready(function() {

topiclistview = $j('[data-tid]').length;

// check if data-tid exists
if (topiclistview > 0) {
//set vars
var tids = $j('[data-tid]');
var tids_array = [];
//get the data attribute values and put them in an array
$j(tids).each(function(index, item) {
tids_array.push($j(item).data('tid'));
});
//run over all tr with the class .col_f_content and append the attribute value
$j('.col_f_content').each(function(index, item){
$j('<span>'+tids_array[index]+'</span>').appendTo($j(item));
//console.log('tr item'+tids_array[index]);
});

}



});

最佳答案

性能方面?这可能是一个很好的镜头:

// iterate over all elements having the data-tid attribute
$("[data-tid]").each(function() {
// Create our span. No need for a jQuery wrapper.
var span = document.createElement("span");
// Set the span text. No need to involve jQuery's data() function
span.appendChild(document.createTextNode(this.getAttribute("data-tid")));
// Add the span to your second cell (col_f_content). This should be way faster
// than creating a new jQuery object via class selector.
this.cells[1].appendChild(span);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr data-tid="3">
<td class="col_f_icon">aaa</td>
<td class="col_f_content">fdsfdsf</td>
</tr>
<tr data-tid="2">
<td class="col_f_icon">aaa</td>
<td class="col_f_content">fdsfdsf</td>
</tr>
<tr data-tid="5">
<td class="col_f_icon">aaa</td>
<td class="col_f_content">fdsfdsf</td>
</tr>
<tr data-tid="6">
<td class="col_f_icon">aaa</td>
<td class="col_f_content">fdsfdsf</td>
</tr>
</table>

或者,根据您的需要,您可以仅使用 CSS 实现类似的效果:

tr[data-tid]:after {
display: table-cell;
vertical-align: middle;
content: attr(data-tid);
}
<table>
<tr data-tid="3">
<td class="col_f_icon">aaa</td>
<td class="col_f_content">fdsfdsf</td>
</tr>
<tr data-tid="2">
<td class="col_f_icon">aaa</td>
<td class="col_f_content">fdsfdsf</td>
</tr>
<tr data-tid="5">
<td class="col_f_icon">aaa</td>
<td class="col_f_content">fdsfdsf</td>
</tr>
<tr data-tid="6">
<td class="col_f_icon">aaa</td>
<td class="col_f_content">fdsfdsf</td>
</tr>
</table>

关于javascript - 获取数据属性并追加优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29167254/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com