本文分享一個透過 jQuery 查找指定鏈接文字並據此替換其屬性的實例,可用於分頁導航等需要根據文字內容動態設置鏈接的場景。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery鏈接文字替換屬性</title>
<script language="JavaScript" src="jquery-1.7.2.min.js"></script>
<script language="JavaScript" type="text/JavaScript">
$(document).ready(function(e) {
var aa = $('a font[title$="首頁"]').html();
if(aa=='首頁'){
$('.page').find('a').eq(0).attr("href", "/page/?type=index");
}
});
</script>
</head>
<body>
<div class="page">
<a href="#"><font title="首頁">首頁</font></a>
<a href="#">上一頁</a>
<a href="#">當前頁</a>
<a href="#">下一頁</a>
<a href="#">尾頁</a>
</div>
</body>
</html>
核心思路是先透過選擇器找到目標元素並取出其文字進行判斷,符合條件時再用 attr() 方法為對應鏈接設置新的 href 屬性。
希望這個 jQuery 查找鏈接文字並替換屬性的方法對大家有所幫助。