当我在Angular中加载动态组件时,jQuery无法正常工作 [英] jQuery not working when I load dynamic component in Angular

查看:86
本文介绍了当我在Angular中加载动态组件时,jQuery无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在Angular中实现了动态组件,每当加载动态组件时,其相应的jQuery都无法正常工作。相同的jQuery脚本在其他地方工作。

I have implemented dynamic components in Angular and whenever a dynamic component is loaded its corresponding jQuery is not working. Same jQuery script is working elsewhere.

这是我的动态组件加载的地方:

This is where my dynamic component loads:

<div class="listing-table-outer" [@myAwesomeAnimation]='state'>
      <app-dynamic-question [componentData]="componentData"></app-dynamic-question>
    </div>

html将动态加载。

Below html will be loaded dynamically.

<div class="panel panel-default " >
    <div class="panel-body" >
     <h1>{{textLabel}}</h1>
        <p>{{textHeader}}</p>

        <div class="form-inline display-one" role="form">
            <input type="text" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="">
        </div>

        <div class="learn-more magtop10">
            <a> <i class=" glyphicon glyphicon-play"></i> Learn More</a>
        </div>
        <div class="display_advance">
            <div class="well">
                <p>{{textFooter}}</p>
            </div>
        </div>
        <div class="bs-component">
            <a href="#" class="btn panel-theme-clearbutton btn-lg" *ngIf="this.showButton[0].txt_button == 'Clear'">Clear</a>
            <a href="#" class="btn panel-theme-clearbutton btn-lg" *ngIf="this.showButton[1].txt_button == 'Skip'">Skip</a>
            <a href="#" class="btn panel-theme-button btn-lg" *ngIf="this.showButton[2].txt_button == 'Continue'">Continue</a>
        </div>
    </div>
</div>

我写过这个剧本

$(document).ready(function(){
$('.learn-more').click(function() {

    $('.display_advance').slideToggle('1000');
    $("i", this).toggleClass(" glyphicon-play glyphicon-triangle-bottom");
});


});

我检查了这个脚本,它在其他地方工作得很好。

I have checked this script and it is working perfectly elsewhere.

请让我知道为什么会发生这种情况。

Please let me know why this is happening.

推荐答案

As你已经说明了自己,html是动态加载的。这意味着当执行 $(document).ready(function(){...})时,这个html还没有出现。所以你试图将click事件添加到当时不存在的元素。
对于这种情况,有一个叫做事件委托的事情。

As you already stated yourself, the html is loaded dynamically. That means that this html is not yet there when $(document).ready(function() { ... }) is executed. So you're trying to add a click event to an element that doesn't exist at that moment.
For this exact situation there's a thing called event delegation.

而不是

$('.learn-more').on('click', function() { ... });

你会做什么

$(document).on('click', '.learn-more', function() { ... });

这样任何元素下面的元素带有类现在或将来 learn-more 将获得此点击事件。

This way any elements below document with class learn-more, now or in the future, will get this click event.

这篇关于当我在Angular中加载动态组件时,jQuery无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆