2011-11-11 42 views
0

现在,我使用的是这样的:如何使用jQuery在此href属性中添加“#”?

// Scroll to matched dish 
$("#scrolll").click(function() { 
    $("a#scrolll").attr("href", $("li.matched").attr("id")); 
    return false; 
}); 

要添加到li.matcheda#scroll的href属性的ID。 例如,如果li.matched#menu123的ID,a#scrolll看起来就像这样:

<a id="scrolll" href="menu123"> 

但我想使它看起来像这样:

<a id="scrolll" href="#menu123"> 

任何建议,以做到这一点?

回答

4

使用+ operator在开始时加上#

// Scroll to matched dish 
$("#scrolll").click(function() { 
    $("a#scrolll").attr("href", "#" + $("li.matched").attr("id")); 
    return false; 
}); 

此外,因为你从它在事件处理中改变元素,你可以使用$(this)而非重新选择的元素。 (Cyber​​nate首先注意到这个in his answer

+1

西部最快的枪 – alexchenco

2

+运算符附加“#”。

你也可以用$(this).attr取代$("a#scrolll").attr因为代码是在a#scrolll

单击处理试试这个:

$("#scrolll").click(function() { 
    $(this).attr("href", "#" + $("li.matched").attr("id")); 
    return false; 
}); 
+4

+1首先注意到你可以使用'$(this)'' –

2

只需在连接字符串:

// Scroll to matched dish 
$("#scrolll").click(function() { 
    $(this).attr("href", '#' + $("li.matched").attr("id")); 
    return false; 
}); 

您可以使用运算符将+连接在一起。我还用$(this)替换了您的冗余选择器。

另外,小心你的第二个选择器li.matched。您不是100%确定只有一个元素的类别为.matched,所以如果碰巧存在该类别的两个元素,则您的attr("id")可能未定义。