我正在使用两个div。在第一个div中,所有用户都显示在页面上,带有“ADD”按钮选项。通过添加用户,他们将使用jQuery添加到第二个div。但我想确保它们不会被添加两次。我想实现一个条件来检查用户是否已经添加,然后不应该添加它或者应该禁用按钮。我正在编写下面的代码,我在wordpress中使用,但问题与jquery -
有关<?php
/*
Template Name: Users
*/
?>
<style>
.container{
width: 800px;
}
.left{
float:left;
width: 300px;
background: ##66CDAA;
border-right: thick-solid #fff;
}
.right{
overflow: hidden;
width: 500px;
background: powderblue;
}
</style>
<?php
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<div class="container">
<div class="left" id="xyz">
<table>
<tr>
<th>Name</th>
<th>Gravatar Image</th>
<th>Add to Div</th>
</tr>
<?php
$sql ="SELECT * FROM wp_users";
$results = $wpdb->get_results($sql) or die(mysql_error());
foreach( $results as $result ){ ?>
<tr>
<td id="<?php echo $result->ID; ?>">
<?php echo $result->display_name; ?>
</td>
<td>
<?php echo get_avatar( $result->user_email, 42); ?>
</td>
<td>
<input type="button" class="submit" data-id="<?php echo $result->ID; ?>" data-name="<?php echo $result->display_name; ?>" data-image="<?php echo get_avatar_url($result->user_email); ?>" value="ADD"><p style="display:none;">Added</p>
</td>
</tr>
<?php
}
?>
</table>
</div>
<div class="right">
<p>Added Users</p>
<table class="table">
<tr>
<th>Name<th>
<th>Image</th>
</tr>
</table>
</div>
</div>
</main>
</div>
<?php get_footer(); ?>
在我的ajax.js文件中,我将用户添加到第二个div,还有一个取消按钮取消,但在从第二个div取消用户后,我们应该再次能够将用户添加到第二个div。
(function($) {
$(document).ready(function() {
$(".submit").on("click", function(e){
e.preventDefault();
var id = $(this).data('id');
var name = $(this).data('name');
var image = $(this).data('image');
//Here I want to check the condition that if a user is already added then it should not be added.
$('.table').append('<tr id=" ' + id+ ' "><td>' + name + '</td><br><td><img src=" ' + image + ' "></td><td><input type="button" value="Cancel" class="cancel"></td></tr>');
})
})
})(jQuery);
所以,我的问题是如何确定是否已添加用户,然后不应再次添加。为此,我该如何检查。而如果 添加的用户被取消,然后取消按钮disappers并在第一个div中出现添加按钮。如果现在有用户,如何隐藏表格。在我的情况下,我尝试过,但它不起作用。
编辑:在functions.php中,我使用以下代码排入ajax.js文件。
<?php
function umar_scripts(){
wp_enqueue_script( 'main_ajax', get_template_directory_uri() . '/js/ajax.js', array('jquery'), '', true);
}
add_action( 'wp_enqueue_scripts', 'umar_scripts' );
答案 0 :(得分:0)
假设您正在向表中的每个User行添加uniqe id,您可以添加一个检查表中是否存在具有该id的行。使用下面的代码:
(function($) {
$(document).ready(function() {
$(".submit").on("click", function(e) {
e.preventDefault();
var id = $(this).data('id');
var name = $(this).data('name');
var image = $(this).data('image');
if ($('table').find('#' + id).length <= 0) {
{
$('.table').append('<tr id=" ' + id + ' "><td>' + name + '</td><br><td><img src=" ' + image + ' "></td><td><input type="button" value="Cancel" class="cancel"></td></tr>');
}
})
})
})(jQuery);
答案 1 :(得分:0)
以下是检查用户是否存在的方法:
if($('.table td#' + id).length) { // user exists }
else { // user doesn't exist }