[英]Making an entire div clickable using jQuery (Wordpress)
我有一個 wordpress 安裝,正在嘗試創建一個函數,根據其中的 href 使整個 div 可點擊。 我找到了很多文檔告訴我要這樣做。
jQuery(".myBox").click(function($) {
window.location = $(this).find("a").attr("href");
return false;
});
但它不起作用,點擊后沒有任何反應。 奇怪的是,如果我這樣做只是作為一個測試
jQuery(".myBox").click(function($) {
window.location = "http://www.google.com"
return false;
});
然后它確實起作用了,div 將重定向到 google.com,所以它似乎不是我實現腳本的方式的問題。 我在某個地方用第一種方法出錯了嗎? 這是我的 HTML
<div class="myBox">
<p><a href="http://www.example.com/notworking">This whole box should link but doesn't.</a></p>
</div>
在HTML,̶你沒有必要的元素與類̶ ̶m̶y̶B̶o̶x̶
(這是固定在一個編輯)
不過有幾點,你真的需要jQuery嗎? 這就像用錘子殺死一只蒼蠅。 通常對於“完全可點擊的元素”,您可以使用relative
定位的父級、 absolute
定位的鏈接,並將其設置為頂部/左側和 100% 寬度和高度。
.myBox{padding:10px;border:1px solid #ccc;position: relative;} .cover{ position: absolute; top: 0; left: 0; width: 100%; height: 100%; } .cover:hover { background:rgba(0,95,235,.25);
<p class="myBox">This whole box should link.<a href="#" class="cover"></a></p>
您還可以選擇將錨點放在要鏈接的任何內容之外(根據您的編輯,我認為這可能不是一個選項?):
.myBox{padding:10px;border:1px solid #ccc;position: relative;}
<a href="#"><p class="myBox">This whole box should link.</p>
如果出於某種原因確實需要 jQuery,則可以在一個ready
函數中處理所有 jQuery 函數,並將單擊事件處理程序傳遞給它。 (注意,您還應該處理鏈接不存在的情況,否則如果點擊它,您會將用戶發送到一個空白/損壞的 URL):
jQuery(document).ready(function($){ $('.myBox').on('click', function(){ var location = $(this).find('a').attr('href'); if( location ) window.location = location; }); });
.myBox{ padding: 10px; border: 10px; } .myBox:hover {cursor: pointer; background: #0095ee;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="myBox"> <p>This is test.<a href="https://example.com/">This is a link</a></p> </div> <div class="myBox"> <p>This is with no link</p> </div>
jQuery(".myBox").click(function($) {
window.location = $(this).find("a").attr("href");
return false;
});
您的問題是您在點擊事件處理程序的參數上有$
。 傳入的變量是生成的Event
,而不是jQuery
。 有幾種方法可以解決這個問題。
jQuery(".myBox").click(function() {
window.location = jQuery(this).find("a").attr("href");
return false;
});
var $ = jQuery;
$(".myBox").click(function() {
window.location = $(this).find("a").attr("href");
return false;
});
jQuery(document).ready(function($){
$(".myBox").click(function() {
window.location = $(this).find("a").attr("href");
return false;
});
});
(function($){
$(".myBox").click(function() {
window.location = $(this).find("a").attr("href");
return false;
});
}(jQuery));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.