重新创建动态选择控制选项jQuery

时间:2018-03-27 13:47:47

标签: javascript jquery

我有以下功能,我用它来填充带有选项的Select控件。我从文档中的对象中获取值,如果满足条件,则将另一个值作为选项投入Select Control ...

function dispatchList() {

//grab list element
var list = document.getElementById("techName");

//foreach div assigned the .square class,
$('.square').each(function () {

    //convert each div with .square class toString
    var square = $(this).html().toString();

    //grab availability value
    var availability = $(this).find('tr:eq(4)').find('td').text();

    //grab IP 
    var online = $(this).find('tr:eq(3)').find('td').text()

//if availability and IP values meet below condition...
    if ((availability === "True") && (online.indexOf("10.") === 0)) {

    //grab the name value from this div
        var availableName = $(this).find('tr:eq(0)').find('td').text();

        //create a new option element
        var item = document.createElement("option");

        //create a new text node containing the name of the tech
        item.appendChild(document.createTextNode(availableName));

        //append the new text node (option) to our select control
        list.appendChild(item);

    }

})

}

此功能运行良好,但在文档准备就绪时运行。我需要它在文档准备好时运行,但也需要重新创建此列表而不刷新页面。理想情况下,可以使用div上的click事件清空并重新创建select控件。

这是我一直在努力的部分。我有以下点击事件,将它链接起来是有意义的,但我还没能解决它...

function availability() {

//for each element with a class of .square...
$('.square').each(function () {

    //grab the id of each input element (button) contained in each .square div...
    var btnId = $(this).find("input").attr("id");

    //when .square div is clicked, also click it's associated asp button...
    $(this).on('click', function (clickEvent) {

        document.getElementById(btnId).click();

    //****AND ALSO TRIGGER THE dispatchList() FUNCTION TO REBUILD THE #techName LIST****

    })

})

}

这可以在没有AJAX或其他一些帖子的情况下完成吗?

首先需要清空#techName列表,然后重建吗?

感谢您的任何建议!

1 个答案:

答案 0 :(得分:0)

$(document).ready(function(){
    $(".square").on('click', function (clickEvent) {
             var el = clickEvent.target || clickEvent.srcElement

            document.getElementById($(el).find('input').attr("id")).click();
            dispatchList();
    }) 
})

这就是我能用给定问题做的一切。我没有测试代码。你可以给小提琴或任何东西进行测试。此功能也在浏览器中编写。