jQuery将文本从span标记复制到另一个span标记

时间:2021-12-02 08:45:52

Here's what I'm trying to do(slider):Image screenshot

这是我正在尝试做的事情(滑块):图片截图

I'm trying to copy the test from the span that has the class of .panel-title to the span with the class of .duplicate-test.

我正在尝试将具有.panel-title类的跨度的测试复制到具有.duplicate-test类的span。

My HTML code is

我的HTML代码是

<div class="item">
  <a href="./">
   <div class="panel-img">
    <img src="_assets_/images/panel-event.png" alt="">
   </div><!-- /.panel-img -->
   <div class="panel-info">
    <div><p class="duplicate-test"></p></div>
    <span class="panel-title">upcoming events</span>
   </div><!-- /.panel-info -->
  </a>
</div><!-- /.item -->

My jQuery code is

我的jQuery代码是

$('.duplicate-test').text($(this).find('.panel-title').text());

It is getting the text from all spans with the class of .panel-title. Is there something wrong with my jQuery code?

它使用.panel-title类来获取所有跨度的文本。我的jQuery代码有问题吗?

2 个解决方案

#1


1  

Try this:

$('.duplicate-test').each(function() {
    $(this).text($(this).parent().next('.panel-title').text());
});

#2


1  

The issue is with your DOM traversal and usage of this.

问题在于你的DOM遍历和使用。

Assuming there's no outer scope of the snippet you've shown, this will refer to the window, not the current .duplicate-test element. To do what you require, you need to pass the text() method a function. From there you can traverse to find the element you want:

假设您没有显示的片段的外部范围,这将引用窗口,而不是当前的.duplicate-test元素。要执行您需要的操作,您需要将text()方法传递给函数。从那里你可以遍历找到你想要的元素:

$('.duplicate-test').text(function() {
    return $(this).closest('.panel-info').find('.panel-title').text();
});

Working example

#1


1  

Try this:

$('.duplicate-test').each(function() {
    $(this).text($(this).parent().next('.panel-title').text());
});

#2


1  

The issue is with your DOM traversal and usage of this.

问题在于你的DOM遍历和使用。

Assuming there's no outer scope of the snippet you've shown, this will refer to the window, not the current .duplicate-test element. To do what you require, you need to pass the text() method a function. From there you can traverse to find the element you want:

假设您没有显示的片段的外部范围,这将引用窗口,而不是当前的.duplicate-test元素。要执行您需要的操作,您需要将text()方法传递给函数。从那里你可以遍历找到你想要的元素:

$('.duplicate-test').text(function() {
    return $(this).closest('.panel-info').find('.panel-title').text();
});

Working example