[英]Manipulate href using jquery
我需要使用jquery在客戶端設置單個類的href URL(social-links-twitter,social-links-facebook,social-links-linkedin)。 如何捕獲href用戶單擊的內容,然后設置網址?
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<!--JQuery-->
<script type="text/javascript" src="http://components.nhmwebdev.co.uk/scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(".profile li a").click(function (e) {
e.preventDefault();
var title = $(this).attr("title");
if (title == "pFacebook") $(this).attr("href", "yourHrefValueForFacebook");
});
</script>
</head>
<body>
<ul class="no-list social-links profile overflow-fix clear-fix push50">
<li class="social-links-twitter">
<a href="#" title="pTwitter">t</a>
</li>
<li class="social-links-facebook">
<a href="#" title="pFacebook">f</a>
</li>
<li class="social-links-linkedin">
<a href="#" title="pLinkedin">l</a>
</li>
</ul>
</body>
</html>
將通用處理程序綁定到該列表,並檢查錨點title
屬性:
$(".social-links li a").click(function(e) {
e.preventDefault();
var title = $(this).attr("title");
if (title == "Facebook") $(this).attr("href", "yourHrefValueForFacebook");
});
您可以使用$(selector).attr("href")
獲取href,並使用$(selector).attr("href", "newurl")
進行設置。
例如:
$(".social-links-twitter a").attr("href");
將獲得您的社交鏈接-推特鏈接的href。
或者嘗試一下,這樣就不需要if語句
$(document).ready(function () {
$(".social-links a[title=Facebook]").attr("href", "yourHrefValueForFacebook");
});
嘗試這個 !
$(document).ready(function(){
$('.social-links a').click(function(e){
switch($(this).attr('title')){
case 'pTwitter':
$(this).attr('href','yourTwitterUrl');
break;
case 'pFacebook':
$(this).attr('href','yourFacbookUrl');
break;
case 'pLinkedin':
$(this).attr('href','yourLinkedinUrl');
break;
default:
e.preventDefault();
break;
}
});
});
不確定您要達到的目標。 但是,您可以像這樣將邏輯移至.ready(),而不是使用.click。
$(document).ready(function(){
$(".no-list li a").each(function(e,v){
//e.preventDefault();
//alert($(v));
var title = $(v).attr("title");
if (title == "pFacebook") $(v).attr("href", "http://facebook.com");
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.