2017-07-07 105 views
0

我有一個導航列表以及單獨的標題和段落的文本。每個列表項都有自己的標題和文本。當您將鼠標懸停在導航項上時,我想要切換主要標題和文字。從子元素jquery獲取文本

的jsfiddle

目前我的代碼顯示的所有文本。我只想顯示類名.spot_titles中發現的H1 & P文本:https://jsfiddle.net/d28zh777/

爲了說明我想要實現:

enter image description here

當你將鼠標懸停在粉刺或油性或什麼上面的標題和文字應該更改爲您正在徘徊的任何項目。這是活動狀態,我想要實現:

enter image description here

jQuery的

// Get the original content 
var main_url = $(".index__hero-image").css('background-image'); 
var main_title = $(".index__hero-image h1").text(); 
var main_text = $(".index__hero-image p").text(); 

$(".index__spot").hover(function() { 
    var image_url = $(this).css('background-image'); 
    // These vars below are wrong I think. 
    var spottitle = $(this).text(); 
    var spottext = $(this).text(); 

    $(".index__hero-image").css('background-image', image_url); 
    $(".index__hero-image h1").text(spottitle); 
    $(".index__hero-image p").text(spottext); 
}, 
function() { 
    // Display original content when nothing hovered 
    $(".index__hero-image").css('background-image', main_url); 
    $(".index__hero-image h1").text(main_title); 
    $(".index__hero-image p").text(main_text); 
}); 

HTML

<div class=" index__text-block"> 
    <h1>Original headline</h1> 
    <p>Original text block goes here</p> 
</div> 

<div class="solutions-bar"> 
<a href="acne.html" class="index__spot" style="background-image: url('http://placekitten.com/700/700');"> 
<!-- Ignore next 3 lines/Create the icon in the link list --> 
<img src="icon.png"> 
<h6 class="content-1">Acne</h6> 
<h6 class="content-2">Shop Now</h6> 

<!-- Use this text to replace that in index__text-block --> 
<div class="spot_titles"> 
    <h1>Acne headline</h1> 
    <p> 
    Some text relating to acne 
    </p> 
</div> 

回答

3

更改此行:

var spottitle = $(this).text(); 
var spottext = $(this).text(); 

這樣:

var spottitle = $(this).find('.spot_titles h1').text(); 
var spottext = $(this).find('.spot_titles p').text(); 

這會得到h1裏面的.spot_titlesp內部.spot_titles

您可以通過jQuery API Documentation瞭解更多關於find()的信息。

+0

我的天啊,那麼簡單!謝謝! – egr103

1

當你需要定位的子元素的文字,所以使用.find()與有效的選擇

// These vars below are wrong I think. 
var spottitle = $(this).find('.spot_titles h1').text(); 
var spottext = $(this).find('.spot_titles p').text(); 

Fiddle