jQuery .load() 函数从 <img> WordPress 帖子中去除标签



我在使用 jQuery.load()动态加载的 HTMLdiv 中显示图像时遇到问题。我目前使用的jQuery函数包含在下面:

jQuery(document).ready(function(e) {
// Past sendout nav trigger function
e( ".btn--nav-trigger" ).click(function() {
e( this ).toggleClass( "btn--nav-trigger-active" );
e( ".sendout__list" ).toggleClass( "sendout__list--open" );
});
// AJAX .load function for sendout post content
e( ".sendout-link" ).click(function() {     
e( ".btn--nav-trigger" ).toggleClass( "btn--nav-trigger-active" );
e( ".sendout__list" ).toggleClass( "sendout__list--open" );
var post_url = e( this ).attr( "href" );
e( "#sendout-container" ).html( '<div class="loading"></div>' );
e( "#sendout-container" ).load( post_url + "#sendout-content", function( response, status, xhr ) {
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
e( "#sendout-container" ).html( msg + xhr.status + " " + xhr.statusText );
}
});
return false;
});
});

该函数成功地从选定的WordPress帖子中加载文本和YouTube iframe,但它总是剥离图像。

该函数的href属性正在使用WordPress中的<?php the_permalink(); ?>。单个帖子正确加载,但具有.load()功能的某些内容正在剥离完整的<img>标签。

更新

看起来包含图像的整个div 也被剥离了。不知道为什么会这样。我已经包含了WordPress HTML/PHP代码,该代码在使用下面的.load()功能时被完全剥离。此代码使用 WordPress/PHP 正确显示。

<?php if(get_field( 'meme_one_image' )): ?>
<div class="sendout__row sendout--meme">
<?php 
$memeOneImage = get_field( 'meme_one_image' );
if( !empty($memeOneImage) ): ?>
<img src="<?php echo $memeOneImage['url']; ?>" alt="<?php echo $memeOneImage['alt']; ?>" />
<div class="sendout--meme_share">
<h4>Share this meme</h4>
<a href="http://www.facebook.com/sharer/sharer.php?u=<?php echo $memeOneImage['url']; ?>" class="button">Facebook</a>
<a href="http://twitter.com/intent/tweet?text=<?php echo $memeOneImage['title'] .' : '. $memeOneImage['url']; ?>" class="button">Twitter</a>
<button class="button copy-button" data-clipboard-text="<?php echo $memeOneImage['url']; ?>">Copy URL</button>
</div>
<?php endif; ?>
</div>
<?php endif; ?>

更新二

我已经修复了我的主题文件和 JavaScript 以使用正确的元素来动态加载帖子类型的内容块。我已经更新了我的.load();函数,以实现亚历山大·奥马拉建议的修复程序。

图像现在正在通过.load();加载。

根据您的描述,您正在尝试将整个HTML文档加载到另一个HTML文档中,这真的很奇怪,并且可能容易出错。

jQuery.load方法用于加载 HTML 内容并将其放入另一个元素中。通常,HTML 内容将仅包含所需的内容,而不包含带有<html><head><body>标记的完整文档。

作为解决方案,您可能希望使用jQuery.load的片段加载功能来指定页面中要使用的元素的 ID,而不是完整文档。

例:

e( "#sendout-container" ).load( post_url + ' #some-element-id', function( response, status, xhr ) {

或者,您可以使用jQuery.ajax加载 HTML 文档并提取要使用的元素的 HTML。

例:

$.ajax({
// Example URL.
url: 'https://cors-anywhere.herokuapp.com/https://example.com/'
}).done(function(data) {
// Parse the HTML document.
var doc = (new DOMParser()).parseFromString(data, 'text/html');
// Select some content from the document.
var body = $(doc).find('body').html();
// Put that content in an element.
$('#content').html(body);
});
#content {
border: solid black 2px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content">
Loading...
</div>

最新更新