2016-12-28 62 views
0

我想弄清楚如何添加一個樣式到鏈接&如果它有一個特定的類追加文本。如果鏈接有類,應用樣式+附加文本

例如

$("a").hasClass("Woohoo")); 
$(".Woohoo").css({ font-style: "italic" }); 
$('.Woohoo').append('Some text'); 
} 

<a href=#">link 1</a> 
<a class="Woohoo" href=#">link 2</a> 
<a href=#">link 2</a> 

應該輸出:

鏈接2中的某些文本

回答

2

您應該使用camelCase的聯用屬性,並使用與Class Selector (「.class」)一起Element Selector (「element」)目標所需的元素。

$("a.Woohoo").css({ fontStyle: "italic" }).append('Some text'); 

OR

$("a.Woohoo").css({ "font-style": "italic" }).append('Some text'); 

$("a.Woohoo").css({ 
 
    fontStyle: "italic" 
 
}).append('Some text');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<a href=#">link 1</a> 
 
<a class="Woohoo" href=#">link 2</a> 
 
<a href=# ">link 2</a>

1

與類簡單地選擇鏈接,做剩下的事情。該物業應該被引用,因爲它包含-,或者使用隨附的fontStyle代替。

$("a.Woohoo").css({ 
 
    'font-style': "italic" 
 
}).append('Some text');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<a href=# ">link 1</a> 
 
<a class="Woohoo " href=#">link 2</a> 
 
<a href=# ">link 2</a>

0

,或者你可以通過與該類別中的所有鏈接元素循環

$("a").each(function() { 
    if ($(this).hasClass("Woohoo")) { 
     // do some magic here 
    } 
}); 

或者更好

$("a.Woohoo").each(function() { 
    // do some magic here 
}); 

但僅僅

$("a.Woohoo").css(... //etc 

應該做你想做的事