【发布时间】:2019-05-10 22:46:39
【问题描述】:
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);
};
});
RESULT:这会将 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);
};
});
RESULT: 这会正确地在每个具有描述类的元素之前呈现工具提示,但我尝试设置它的 title 属性仍然为空(即使将 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' 属性?
【问题讨论】:
-
您是否考虑过在脚本中使用初始循环来添加您想要的唯一 ID ..而不是复杂的解决方法?
标签: javascript jquery class element title