jQuery/Javascript 当现有元素只有 类,没有 ID 时,将唯一元素添加到其他元素

jQuery/Javascript add unique element to other elements when existing elements only have classes, no IDs

Wordpress 主题允许站点管理员创建包含每个字段的 "description" 的表单。描述没有唯一的 ID,只有一个常见的 class:'description.' 他们看起来像这样:

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

我没有像主题那样在每个字段标签内联显示这些描述,而是将描述 class 隐藏为 CSS (display:none;) 并尝试创建一个将描述作为其 'title' 属性 的跨度,以便 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 隐藏了描述字段,并尝试了各种方法在 'description' class 的元素之前或之后添加跨度。预计我最终会遍历这些元素中的每一个,我首先尝试仅使用一个字段(第二个字段的描述为 class)取得成功。这是我所做的许多尝试的两个示例,他们的结果:

示例尝试 #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);
        };
 });

结果: 这会在每个具有描述 class 的元素之前正确呈现工具提示范围,但我尝试设置它的标题属性仍然为空(即使将 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 设置为它之前的新元素的 'title' 属性?

这是一个解决方案,它使用 .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>