js動態追加的元素如何觸發事件


一般通過js或者jQuery動態添加的元素標簽,通過該元素標簽、class、id觸發事件,是無效的。如下所示:

<body>
<input type="text" class="ceshi" />
<input type="text" class="ceshi" />
<input type="text" class="ceshi" />
<button onclick="addLine();">點擊添加</button>

<script>
    function addLine() {
        var html = "<input type='text' class='ceshi' />";
        $('.ceshi:last').after(html);
    }
    $(".ceshi").on('focus', function () {
        $(this).val(111);
    });
</script>
</body>

 

在既有的<input>后面再通過按鈕點擊事件,在js中動態添加一個<input>元素,我們通過頁面操作可以發現,既有的元素聚焦后輸入框內會添加“111”,而js添加的第四個輸入框元素,聚焦后並不會觸發focus事件。如圖所示:

如果想要觸發新標簽的事件,解決方法有兩種:

(1)在標簽內添加事件觸發方法,例如:<a onclick="test();"></a>

<body>
<input type="text" class="ceshi" onfocus="test(this);"/>
<input type="text" class="ceshi" onfocus="test(this);"/>
<input type="text" class="ceshi" onfocus="test(this);"/>
<button onclick="addLine();">點擊添加</button>

<script>
function addLine() {
var html = "<input type='text' class='ceshi' onfocus='test(this);'/>";
$('.ceshi:last').after(html);
}

function test(param) {
$(param).val(111);
}
//$(".ceshi").on('focus', function () {
// $(this).val(111);
//});
</script>
</body>

 

 效果如圖所示,聚焦到第四個動態添加的輸入框時,可觸發聚焦事件。

 

(2)調用jQuery的delegate函數,delegate函數可以根據特定的根元素,把一個或者多個事件注冊到指定的元素上,不論這個元素現在是否存在。

<body>
<input type="text" class="ceshi"/>
<input type="text" class="ceshi"/>
<input type="text" class="ceshi"/>
<button onclick="addLine();">點擊添加</button>

<script>
    function addLine() {
        var html = "<input type='text' class='ceshi'/>";
        $('.ceshi:last').after(html);
    }
    $(function () {
        $("body").delegate("input",
            "focus",
            function () {
                $(this).val(111);
            });
    });

    //function test(param) {
    //    $(param).val(111);
    //}

    //$(".ceshi").on('focus', function () {
    //    $(this).val(111);
    //});
</script>
</body>

 

效果圖和方法(1)是一致,不再贅現。

使用此方法時,如果需要多次變更綁定的事件,需要先解除綁定后才能再次綁定事件,解除綁定的方法:

$("body").undelegate();

 

以上就是兩種解決動態添加標簽的事件綁定方法啦,感謝閱讀!

 /******************************我是可愛的分割線**********************************/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM