2017-03-08 92 views
0

我在圖庫中設置了一系列鏈接,我需要一種向用戶顯示顏色的方法。目前,顏色名稱存儲在圖庫中圖像鏈接的href標題中。獲取href標題並點擊更改

<div class="select-option swatch-wrapper selected" data-attribute="pa_luxcraft-2" data-value="redblack"> 
<a href="#" style="width:32px;height:32px;" title="Red/Black" class="swatch-anchor"><img src="/ay/wp-content/uploads/2017/01/Center-Table-Red-Black-32x32.jpg" alt="thumbnail" class="wp-post-image swatch-photopa_luxcraft-2_ swatch-img" width="32" height="32" data-pin-nopin="true"></a> 
</div> 

在這種情況下,它是紅/黑的顏色

每次圖像被點擊它被分配之類的「選擇」

我知道我能拿到冠軍了簡單變量的

var title = $(this).attr('title'); 

但我不確定如何得到它時選擇的類被應用。

+0

你的意思'$(本).hasClass( '選擇')'? –

回答

1

我收錄了一些幫助你開始的例子。

<div class="displayToUser"></div> 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> 
<script> 

$("a").click (function() { 
    $(document).css("background",$(this).attr("title")); //set's background to color, just to let you know how to do that. 
    $(this).attr("title","new title"); //changes title if that's what you want 
    $(".displayToUser").html(
     $(this).attr("title") 
    ); // sets an element to show the contents of title, just so that you know how to do that 
    $(this).hasClass("selected"); //if you want to check to see if it has the class selected 
    $(this).addClass("selected"); //to add the class selected, if that's what you're looking for. 
}); 

</script> 
1
var color; 

if ($(this).hasClass('selected')) { 
    color = $(this).attr('title'); 
} 

and so on... 
1
var valueoftitle = $('.selected')[<your_index>].attr('title'); 

編輯:

隨着$('.selected')你得到一個數組回來了所有類.selected的元素。然後,您可以使用含有您要訪問的元素的索引的squary括號訪問這些元素。在此之後,您就擁有了該元素,您可以隨意使用它,如下例所示:.attr('title'),這會讓您回到屬性「標題」的值。你可以用任何方式像for循環,foreach循環或內聯索引一樣使用它。

+0

一些上下文或解釋將是優選的。 –

+0

你走了,希望這可以幫助你。請問我是否有更多問題... – broodjetom

0

您提到在點擊圖像時應用選定的類。假設你有一個綁定到圖像的點擊處理程序,你可以從父鏈接中獲取標題屬性$(this).parent('a').attr('title')