使用.innerHTML更新数组,删除/添加时出现问题

时间:2019-03-14 16:33:15

标签: javascript php jquery html arrays

当用户添加/删除项目时,尝试使我的阵列动态更新到前端。

用于前端的HTML / PHP:

<div class="row">
    <div class="col-12">

        <div class="custom--css_pills">
            <span class="tag filtering">Edit Products</span>
            <span id="pills--container"></span>
        </div>

        <?php 

            $items = get_posts( array (  
                'post_type'         =>  array('products'),
                'posts_per_page' => -1  
            )); 
            echo '<div class="enquire--surround_div">';
            foreach($items as $item) {
                echo '<input class="enquiry--add_chk" type="checkbox" value="'.$item->post_title.'" id="'.$item->post_title.'" />  
                <label for="'.$item->post_title.'">'.$item->post_title.'</label>';  
            }
            echo '</div>';

        ?>

    </div>
</div>

到目前为止,我已经设置好数组

var pills = ["test","test2"];

然后设置一个循环遍历此数组并回显div的函数,其中包含数组项和关闭图标

function looparray(){

var str = '';

pills.forEach(function(pill) {
        str += '<div class="tag">'
        str += '<span>' + pill + '</span>';
        str += '<span class="tag-exit"></span>';
        str += '</div>';
}); 

// Echo
    document.getElementById("pills--container").innerHTML = str;
}

然后在加载时调用此函数

looparray();

然后单击单选按钮(前端)。哪个会添加到数组中或删除,取决于是否选中了该复选框

$('.enquiry--add_chk').click(function(){

    $valuetoaddcolour = $(this).next();
    $valuetoaddcolour.toggleClass('enquiry--tabs_colour')

    $valuetoadd = $(this).next().text();

    if ( $(this).is(':checked')) {
        console.log('notfilled');
        pills.push($valuetoadd);
        console.log(pills);
    }
    else{
        pills.splice( $.inArray($valuetoadd, pills), 1 );
        console.log(pills);   
    }

    looparray();

});

然后关闭,以从数组中删除选定的对象。

//On close..
$('.tag-exit').click(function() {

    $valuetoremove = $(this).parent(); // Get parent to hide (surround div)
    $valuetoremovetext = $(this).parent().text(); // Get text to remove from array

    // remove from array
    pills.splice( $.inArray($valuetoremovetext, pills), 1 );
    $valuetoremove.hide(); // Hide the pill

    looparray();

});

现在的问题是,当我第一次选择删除时,它将运行良好。如果我然后添加一个项目,然后尝试通过.tag出口删除,则它不会运行该功能。我将其范围缩小到looparray();导致问题,但看不到是什么原因。我所能想到的就是擦除数据并重新添加,这可能会导致预定义功能出现问题?

我放了一些Codepen以更好地理解。 https://codepen.io/anon/pen/QoQrZw

1 个答案:

答案 0 :(得分:0)

正如@avraham所说,这是由于DOM中没有该元素。

通过添加以下内容来修复:

//On close..
$('body').on('click', '.tag-exit', function () {

// $('.tag-exit').click(function() {

    $valuetoremove = $(this).parent(); // Get parent to hide (surround div)
    $valuetoremovetext = $(this).parent().text(); // Get text to remove from array

    // remove from array
    pills.splice( $.inArray($valuetoremovetext, pills), 1 );
    $valuetoremove.hide(); // Hide the pill

    looparray();

});