2012-02-01 48 views
0

我想使用jquery更改標籤的href。更改href爲<a>不能正常工作

這是html代碼:

<a href="exampleurl" id="a_theme" onClick="return activate_theme();">Click</a> 

這是jQuery代碼:

function activate_theme(){ 
    $("#a_theme")).attr("href", "new url"); 
} 

它顯示了一個錯誤:

activate_theme is not defined 
+2

你的函數有一個語法錯誤(在你的jQuery選擇器中有一個額外的關閉元素)。 – jdigital 2012-02-01 05:51:02

回答

0

1路:

$(function(){ 
$("#a_theme").click(
    function(){ 
     $("#a_theme").attr("href", "new url"); 
    } 
); 
}); 

<a href="#" id="a_theme">Click</a> 

第二個辦法:

function activate_theme(){ 
    $("#a_theme").attr("href", "new url"); 
} 


<a href="#" id="a_theme" onClick="activate_theme()">Click</a> 
0

你做錯了,可能是因爲activate_theme()在您的onClick處理程序不可訪問的範圍內定義。你也有一個語法錯誤(jQuery調用中的雙重))。

只是這個替換代碼:

<a href="exampleurl" id="a_theme">Click</a> 

,並用JavaScript:

$(function(){ 
    $("#a_theme").attr("href", "new url"); 
}); 

將被儘快執行的DOM準備就緒,並將取代href爲指定的鏈接。

觀看演示在這裏工作:http://jsfiddle.net/tadeck/mHtHc/

0
try with this also: 

$('#a_theme').click(function(){ 
$(this).attr('href', 'new_url'); 
}); 

但如果你有一個以上的ID名稱相同則:

$('#a_theme').each(function(i, e){ 
    $(this).click(function(){ 
    //same url on all '#a_theme' on click 
    $(this).attr('href', 'new_url'); 
    }); 
});