gpt4 book ai didi

javascript - Wordpress 在不刷新页面的情况下获取图像类别

转载 作者:行者123 更新时间:2023-11-28 05:51:09 25 4
gpt4 key购买 nike

我一直在为摄影师做一个元素。

我正在尝试为照片制作类别列表。像这样: Category of photos

但问题是当我点击一个类别时它会自动刷新网站,这不是我想要的。我想刷新照片,而不是网站。

我尝试在 Javascript 中使用 preventDefault,但它不起作用。

我该如何解决这个问题?

-- Javascript --

function getClick(event) {
event.preventDefault();
}

var getCategory = document.querySelectorAll(".cat a");
for(var i = 0, ilen = getCategory.length; i < ilen; i++) {
getCategory[i].addEventListener("click", getClick);
}

-- HTML--

<div class="cat">
<ul>
<li><a class="recent" href="?assignement=recent">RECENT</a></li>
<li><a class="all" href="?assignement=all">ALL</a></li>
</ul>
</div>

-- PHP Wordpress--

  <?php if($_GET["assignement"] == "recent") : ?>
<?php
$args = array( 'posts_per_page' => 100, 'orderby' => 'date' );
global $post;
$recent_posts = get_posts($args);
foreach($recent_posts as $post) :
?>
<?php if( in_category("photos") ) : ?>
<div class="grid-item hover-item" id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<div class="photo-title">
<?php
if ( is_single() ) {
the_title( '<h2 class="entry-title">', '</h2>' );
} else {
the_title( '<h2 class="entry-title">', '</h2>' );
}
?>
<p>by <a href="Michelle">MICHELLE</a></p>
</div>
<?php add_theme_support( 'post-thumbnails' ); ?>
<?php the_post_thumbnail(); ?>
</div><!-- grid-item -->
<?php endif; ?>
<?php endforeach; ?>
<?php endif; ?>

谢谢

亚乌尔。

最佳答案

  1. preventDefault 可能无法正常工作,因为当您尝试添加事件监听器时页面尚未加载,请尝试如下操作:

window.addEventListener('click', function() {
function getClick(event) {
event.preventDefault();
}

var getCategory = document.querySelectorAll(".cat a");
for (var i = 0, ilen = getCategory.length; i < ilen; i++) {
getCategory[i].addEventListener("click", getClick);
}
});

  1. 即使 preventDefault 确实有效,它也只会阻止页面访问您的 PHP。您需要使用事件处理程序向 PHP url 发出 AJAX 请求,然后将响应注入(inject)页面。类似于:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("your_photos_element").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "your_php_url.php", true);
xhttp.send();

关于javascript - Wordpress 在不刷新页面的情况下获取图像类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37328569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com