我正在嘗試拆分一個陣列,以便可以將資料用作錨點 href 標記。我可以讓陣列登錄控制臺,但每個menu-linkhref 都鏈接到#News.
這是我的代碼:
$(document).ready(function(){
if($('.newsletter-accordion').find('.headline_title').length > 0) {
var all = $(".headline_title").map(function() {
return this.innerHTML;
});
console.log(all);
for(var i = 0; i < all.length; i ) {
$('.headline_title').contents().unwrap().appendTo($('#newsletter-nav ul')).wrap('<li><a href="#' all[i] '" ></a></li>');
console.log(all[i])
}
}
});
我將資料附加到id時事通訊nav中,用作整個頁面的導航。我不確定我是否正確呼叫它 all[i]?
任何幫助,將不勝感激。
更新:
我的 json 控制臺日志。
{"0":"News","1":"Gallery Title","2":"tyest","length":3,"prevObject":{"0":{},"1":{},"2":{},"length":3,"prevObject":{"0":{"location":{"ancestorOrigins":{},"href":"https://croydon.vm/newsletters/4th-march-2022/#News","origin":"https://croydon.vm","protocol":"https:","host":"croydon.vm","hostname":"croydon.vm","port":"","pathname":"/newsletters/4th-march-2022/","search":"","hash":"#News"},"jQuery32100224421490645290161":{"events":{"webkitvisibilitychange":[{"type":"webkitvisibilitychange","origType":"webkitvisibilitychange","guid":11,"namespace":""}],"ready":[{"type":"ready","origType":"ready","guid":7,"namespace":"slick.slick-0"}],"click":[{"type":"click","origType":"click","guid":16,"selector":".accordion-btn","needsContext":false,"namespace":""}]},"focusout":1,"focusin":1},"jQuery360044517605261132511":{"events":{"ajaxSuccess":[{"type":"ajaxSuccess","origType":"ajaxSuccess","guid":1428,"namespace":""}],"touchstart":[{"type":"touchstart","origType":"touchstart","guid":1434,"selector":".qm-resizer","needsContext":false,"namespace":""}],"mousedown":[{"type":"mousedown","origType":"mousedown","guid":1434,"selector":".qm-resizer","needsContext":false,"namespace":""}]}}},"length":1}}}
我也使用靈活的內容,所以這是 html 的塊之一
<section class="newsletter-accordion">
<?php
$headline = get_sub_field('section_headline');
?>
<h1 class="headline_title" id="<?php echo $headline; ?>"><?php echo $headline; ?></h1>
<h1 class="" id="<?php echo $headline; ?>"><?php echo $headline; ?></h1>
<div class="grid_container">
<div class="row single_content__wrapper justify-content-center ">
它稱為 h1 標題標題,此標題標題也出現在其他塊上。
uj5u.com熱心網友回復:
for當你的回圈第一次運行時, .contents().unwrap()...etc 代碼會抓取所有帶有“headline_title”類的專案并將它們移動到導航中,將它們包裝在一個鏈接中。但是,當然,在每一個中,您創建的用于環繞它移動的每個元素的鏈接都使用來自 的第一項all,即“新聞”。
下一次回圈迭代時,沒有什么可以.contents()再抓取了,所以什么也沒有發生。
相反,由于.wrap()我們可以選擇使用回呼函式,其this背景關系變數代表匹配集中的當前元素,我們可以all完全省去回圈:
$('.headline_title').contents().unwrap().appendTo($('#newsletter-nav ul')).wrap(function() {
return '<li><a href="#' $(this).text() '" ></a></li>';
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 class="headline_title">News</h1>
<h1 class="headline_title">Gallery Title</h1>
<h1 class="headline_title">tyest</h1>
<div id="newsletter-nav">
<ul>
</ul>
</div>
檔案:https ://api.jquery.com/wrap/
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/447470.html
標籤:javascript html jQuery
