首页 > 解决方案 > 当现有元素只有类,没有 ID 时,jQuery/Javascript 将唯一元素添加到其他元素

问题描述

Wordpress 主题允许站点管理员创建包含每个字段的“描述”的表单。描述没有唯一的 ID,只有一个公共类:“描述”。它们看起来像这样:

<div class="field-head"><label for="name">Your name</label><small class="description">A unique description for this field.</small></div>

我没有像主题那样在每个字段标签内联显示这些描述,而是使用 CSS (display:none;) 隐藏描述类并尝试创建一个将描述作为其“标题”属性的跨度,以便 jQuery 将将其显示为悬停时的工具提示。

这就是我想要的:

<div class="field-head"><label for="name">Your name</label><span class="tipwrapper" title='A unique description for this field.'>Hover for a tip</span><small class="description">A unique description for this field.</small></div>

我已经成功地使用 CSS 隐藏了描述字段,并尝试了各种方法在具有“描述”类的元素之前或之后添加跨度。预计我最终会迭代这些元素中的每一个,因此我首先尝试仅使用一个字段(第二个具有描述类)来取得成功。以下是我所做的许多尝试及其结果的两个示例:

示例尝试#1:

  jQuery(document).ready(function($){
if (jQuery(('.field-head')[1]) ){
  var tiptext = $('.field-head .description')[1].innerHTML;
  var txt1 = '<span class="tipwrapper">'+tiptext+'</span>';
  $('.field-head .description')[1].before(txt1); 
};
});

结果:这会将 HTML 放在正确的位置,但它不会被渲染,并且只显示为内联文本,如下所示:

<span class="tipwrapper">A unique description for this field.</span>

示例尝试#2:

(我尝试先创建工具提示跨度,然后设置它们的标题):

jQuery(document).ready(function($){
  var txt1 = "<span class='tipwrapper' title=''>Hover for a tip</span>";                   
  $('.field-head .description').before(txt1);
  });
jQuery(document).ready(function($){
     if (jQuery(('.field-head')[1]) ){
var classLength = $('.field-head .description').length;
   var tiptext = $('.field-head .description')[1].innerHTML;
   $(('.field-head .tipwrapper')[1]).attr('title', tiptext);
        };
 });

结果:这会正确地在每个具有描述类的元素之前呈现工具提示,但是我尝试设置它的标题属性仍然为空(即使将 alert(tiptext) 添加到上面的函数中确认变量正在正确获取描述文本。生成的 HTML 是这样的。

<div class="field-head"><label for="name">Your name</label><span class="tooltip" title=''>Hover for a tip</span><small class="description">A unique description for this field.</small></div>

如何将元素中的 html 设置为之前新元素的“标题”属性?

标签: javascriptjqueryclasselementtitle

解决方案


这是一个使用新元素.replaceWith()替换原始small元素的解决方案span

.each()循环用于迭代所有元素.field-head

请参阅代码中的注释。

$(".field-head").each(function() {

  // Get the small element in each field-head and get its text
  var small = $(this).find("small")
  var description = small.text();

  // create a span element...
  var span = $("<span>").addClass("tipwrapper").text("Hover for a tip");
  // And set the title.
  span.attr("title", description);

  // Replace the small with the new span
  small.replaceWith(span);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="field-head"><label for="name">Your name</label><small class="description">A unique description for this field.</small></div>


推荐阅读