【问题标题】:why styles and javascripts code not apply to new added html content为什么样式和 javascripts 代码不适用于新添加的 html 内容
【发布时间】:2019-10-20 02:54:03
【问题描述】:

我使用 ajax 向服务器请求并获得一些 HTML 代码的响应。我得到它并添加到具有 id='conten' 但样式和脚本不适用的 div

这是我的 ajax 请求触发器:

  <li class="catalogs"  catalog_id="<?= $category->id?>"><?= $category->title?></li>

这是我的 ajax 帖子:

//get catalogs
        $('.catalogs').click(function () {
            let catalog_id = this.getAttribute('catalog_id')
            console.log(catalog_id)

            $.ajax({

                url: '/site/catalog',
                type: 'get',
                data: {
                    id: catalog_id
                }
            }).done(function (response) {
                $('#conten').html(response);
            })

        })

这是我在 SiteController 中的操作

    public function actionCatalog($id)
    {
        $products = \common\models\Product::find()->where(['category_id' => $id]);
        $subCategories = \common\models\SubCategory::findAll(['category_id' => $id]);
        return $this->renderAjax('index',[
            'products' => $products,
            'subCategories' => $subCategories,
        ]);
    }

这是我的 id="conten"

 <div id="conten">
     <?= $content?>
 </div>

我的 AppAssets 文件

// css
'css/plugins.css',
        'css/style.css',
        'css/responsive.css'
//js

'js/jquery.js',
        'js/plugins.js',
        'js/functions.js'


【问题讨论】:

  • 你说的是css风格我们没有代码,你怎么知道脚本没有应用?
  • 对于 Javascript 事件,您需要进行事件委托。对于 CSS,它没有任何意义为什么它不起作用。您能否提供一个可重现的示例。
  • 不清楚你期待什么,以及目前正在发生什么。
  • 我的css和js代码都是库
  • 我们不会要求您提供所有库。我们要求一个可重现的例子。只是用最少的代码重现您的问题,以保持清晰。由于您的问题似乎是客户端的问题,您可以轻松创建一个 sn-p。

标签: javascript css ajax yii2


【解决方案1】:

您使用 ajax 加载 JS 和 CSS?如果是这样,这是因为包含所有 css 的 html 页面在文档准备就绪时被加载..它读取所有类并根据它应用的样式表..但是在 ajax 中,我们将另一个页面加载到相同的 html 页面,这次浏览器没有将 html 类映射到样式表,这就是为什么您的 css 不适用于该样式表的原因。

有两种方法可以做到这一点,一种是内联 css,另一种是在加载 ajax 页面后再次加载所有 css 文件。你可以通过 jquery 或 javascript 来完成。

这是一个例子: Is there an easy way to reload css without reloading the page?

【讨论】:

  • $this-&gt;renderAjax() 加载视图以及为视图注册的必要 js 和 css
  • 感谢 looooooot 。这正是我所需要的
猜你喜欢
  • 1970-01-01
  • 2020-06-09
  • 2018-07-08
  • 1970-01-01
  • 2013-03-27
  • 2014-11-19
  • 2015-07-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多