[英]Why isn't my jQuery dynamic link clone working?
我正在嘗試克隆鏈接,以使一系列圖像可點擊的鏈接。 我嘗試使用jQuery中的一些代碼示例-將動態鏈接從一個元素復制到另一個 。 沒用
給出以下HTML代碼:
<ul class="slides">
<li class="views-row views-row-1 views-row-odd views-row-first">
<div>
<img src="https://www.sfmta.com/sites/default/files/styles/home_slide/public/homeslides/2017/Clipper%20on%20Muni-1.png?itok=PPZNHt_N" width="630" height="369" alt="Image with a Clipper Card and illustrated Muni bus with text: Get Clipper and save on Muni." title="Get Clipper and save on Muni" />
</div>
<div class="slider-caption">
<div class="row-fluid">
<div class="span6 offset6">
<div class="slider-caption-inner">
<h2>
<a href="https://www.sfmta.com/about-sfmta/blog/jan-1-muni-fare-changes-include-cash-free-benefits-extended-youth-discounts">New Muni Fare Changes</a>
</h2>
<p>New Muni fares include single-ride savings for using Clipper and MuniMobile.</p>
<a href="https://www.sfmta.com/about-sfmta/blog/jan-1-muni-fare-changes-include-cash-free-benefits-extended-youth-discounts">Learn more</a>
</div>
</div>
</div>
</div>
</li>
... (more list items)
</ul>
我正在尋找以下結果,其中代碼的第4行是唯一更改的行(將img與克隆的錨標記包圍):
<ul class="slides">
<li class="views-row views-row-1 views-row-odd views-row-first">
<div>
<a href="https://www.sfmta.com/about-sfmta/blog/jan-1-muni-fare-changes-include-cash-free-benefits-extended-youth-discounts"><img src="https://www.sfmta.com/sites/default/files/styles/home_slide/public/homeslides/2017/Clipper%20on%20Muni-1.png?itok=PPZNHt_N" width="630" height="369" alt="Image with a Clipper Card and illustrated Muni bus with text: Get Clipper and save on Muni." title="Get Clipper and save on Muni" /></a>
</div>
<div class="slider-caption">
<div class="row-fluid">
<div class="span6 offset6">
<div class="slider-caption-inner">
<h2>
<a href="https://www.sfmta.com/about-sfmta/blog/jan-1-muni-fare-changes-include-cash-free-benefits-extended-youth-discounts">New Muni Fare Changes</a>
</h2>
<p>New Muni fares include single-ride savings for using Clipper and MuniMobile.</p>
<a href="https://www.sfmta.com/about-sfmta/blog/jan-1-muni-fare-changes-include-cash-free-benefits-extended-youth-discounts">Learn more</a>
</div>
</div>
</div>
</div>
</li>
...
</ul>
我根據鏈接的Stack Overflow帖子嘗試了兩種不同的代碼版本:
版本1:
jQuery(document).ready(function() {
"use strict";
jQuery('.slides .views-row .img').wrap(function() {
return jQuery(this).closest('.views-row').find('h2 a').clone().text('');
});
});
版本2:
jQuery(document).ready(function() {
"use strict";
jQuery('.slides .views-row .img').html(function(i,html) {
return $(this).next('h2').find('a').clone().html( html );
});
});
兩種代碼均無效。 列表中的圖像未鏈接。 HTML代碼保持不變。 (在Windows的Firefox和Chrome中測試。)
我的瀏覽器控制台上沒有JavaScript錯誤。 有一個針對jQuery最小化JavaScript本身的警告“不贊成使用getPreventDefault()。請改用defaultPrevented。” 但這已經發生了,並且不會阻止我網站上已經存在的jQuery代碼起作用。
有什么想法/更正嗎?
而是嘗試使用其他方式。
當您嘗試單擊圖像時,請嘗試觸發鏈接上的click事件,因為兩者都具有相同的url。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.