jQuery输出图像标题/描述不起作用?

时间:2018-05-19 14:38:38

标签: jquery wordpress

我是新手编码员。我正在使用Wordpress。我使用此工作代码段在图像下方显示图片标题:

<script>
  jQuery('.ce-image').find('img').after(function(){
    return jQuery('<p class="image-caption">').text(jQuery (this).attr('caption')); }
);

我还要显示图片中的标题和说明字段。但是,当我将标题和描述插入(this.attr(&#39; FIELD HERE&#39;))时,它无效。我被困在为什么。标题和说明字段确实包含数据,但它似乎无法抓住它。

例如,这段代码不会返回任何内容:

<script> jQuery('.ce-image').find('img').after(function() { return jQuery('<p class="image-caption">').text(jQuery (this).attr('title')); }); </script>

左标题和说明字段的语法是否不同?使用alt字段对我有用,标题正在工作,但标题和说明字段不起作用。我可以尝试另一种类似的方法吗?提前感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

试试这个标题:

(1, 'hello world', 'hello test', 'world test'),
(2, 'hello from my sql fiddle', 'hello my sql', 'from fiddle');

这是为了描述:

<script>
 jQuery('.ce-image').find('img').after(function() {
   return jQuery('<p class="image-title">').text(jQuery (this).attr('title'));
 });
</script>

或者,对于所有这些(标题,描述和标题):

&#13;
&#13;
<script>
 jQuery('.ce-image').find('img').after(function() {
   return jQuery('<p class="image-description">').text(jQuery (this).attr('description'));
 });
</script>
&#13;
var $ceImage = jQuery('.ce-image').find('img');
$ceImage.each(function(){
   var image_caption= $(this).attr('caption');
   var image_title = $(this).attr('title');
   var image_description = $(this).attr('description');
   $(this).after('<p class="image-title">' + image_title + '</p><p class="image-caption">' + image_caption + '</p><p class="image-description">' + image_description + '</p>');
});
&#13;
&#13;
&#13;

答案 1 :(得分:0)

或者您可以将标题放在图像上方:

var $ceImage = jQuery('.ce-image').find('img');
$ceImage.each(function(){
   var image_caption= $(this).attr('caption');
   var image_title = $(this).attr('title');
   var image_description = $(this).attr('description');
   $(this).before('<p class="image-title">' + image_title + '</p>');
   $(this).after('<p class="image-caption">' + image_caption + '</p><p class="image-description">' + image_description + '</p>');
});
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ce-image">
  <img src="https://placeimg.com/300/200/people" caption="Caption 1" title="Title 1" description="Description 1">
</div>
<div class="ce-image">
  <img src="https://placeimg.com/300/200/people" caption="Caption 2" title="Title 2" description="Description 2">
</div>