我有以下由WordPress父主题中的functions.php生成的短代码生成的html:
<div class="pricing-table-one left full-width ">
<div class="pricing-table-one-border left">
<div class="pricing-table-one-top pricing-table-green left" style="background:#95705b">
<span style="color:">Restaurant / Café</span>
<p style="color:"></p>
</div>
<div class="pricing-table-one-center pricing-table-white left">
<h5>ONTBIJT</h5>
</div>
<div class="pricing-table-one-center pricing-table-white left">
<h5>LUNCH</h5>
</div>
<div class="pricing-table-one-center pricing-table-white left">
<h5>BRUNCH</h5>
</div>
<div class="pricing-table-one-center pricing-table-white left">
<h5>DINER</h5>
</div>
<div class="pricing-table-one-center pricing-table-white left">
<h5>WEST-FRIESE KOFFIETAFEL</h5>
</div>
<div class="pricing-table-one-center pricing-table-white left">
<h5>SALADESCHOTELS</h5>
</div>
<div class="pricing-table-one-center pricing-table-white left">
<h5>EN NOG VEEL MEER</h5>
</div>
<div class="color-buttons color-button-blue pricing-button">
<a href="mailto:<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="244d4a424b64404b49454d4a0a4a48" rel="noreferrer noopener nofollow">[email protected]</a>?subject=Informatie Restaurant">Voor meer informatie – Email ons</a>
</div>
</div>
</div>
我需要将单元格或包含它的 div 中的标题之一设为 pdf 的链接。我读过here我可以使用 jQuery 在 id 上执行此操作,如下所示:
$("div").click(function(){
window.location=$(this).find("a").attr("href"); return false;
});
但是他只有在你更改 html 时才起作用。我只喜欢 Jquery 或 JavaScript 解决方案。在 CSS Tricks 上我发现了另一个 snippet这可能有帮助
$(".myBox").click(function() {
window.location = $(this).find("a").attr("href");
return false;
});
我只需要将 a 元素更改为 div 并将类更改为 div 的类。但是,我需要使用一些特定的 div(表中的一些元素,但不是全部)来完成此操作,并且它只有一种有用的类:
<div class="pricing-table-one-center pricing-table-white left"><h5>BRUNCH</h5></div>
也许通过关注类为“pricing-table-one”的父 div,然后关注其中的 div。但我仍然需要第 n 个 div 或 h5 标签..
是否可以使用 JavaScript 或 jQuery 来创建 BRUNCH 或其他 h5 标签的链接,或者是否必须更改为 PHP 代码服务器端?
最佳答案
我对他的回答投了赞成票,但是,这里有一个简短的片段来表达我的意思。这是假设您无法控制 html。
$(function () {
// pdf urls and header names
var pdfUrls = {
'BRUNCH': 'http://domain.nl/wp-content/uploads/2015/02/09/x.pdf',
'DINER': 'http://domain.nl/wp-content/uploads/2015/02/09/y.pdf'
};
// loop through each h5 tag within pricing-table-one
$('.pricing-table-one h5').each(function (i, el) {
var header = $(el).text();
// if a header url is found
if (pdfUrls[header]) {
$(el).wrap('<a href="' + pdfUrls[header] + '"></a>');
}
});
});
这是一个 fiddle :http://jsfiddle.net/pbzvszxo/
关于javascript - 使用 JavaScript 将 div 转换为链接,数量有限。有类且没有 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28425641/