2017-07-07 96 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