【问题标题】:Included jQuery does not work on included html包含的 jQuery 不适用于包含的 html
【发布时间】:2018-07-18 12:33:22
【问题描述】:

在我的项目中,我想将 include 用于通用 HTML 部分。但是当我包含一个 HTML 文件时,jQuery 不再工作了。下面是我的代码示例。在这种情况下,我想在此页面中包含介绍文本。警报会起作用,但带有类介绍文本的跨度也将可见,而 main.js 中的代码应使其隐藏。有人有什么想法吗?

HTML 页面

<div id="include-introText"></div>

<script src="main.js"></script>

<script type="text/javascript">

  $('#include-introText').load('intro-text.html', function () {
     // nothing
  });

</script>  

intro-text.html

<span class="intro-text">Hello, this is an intro text</span>

main.js

$('span.intro-text').hide();
alert('test')  

【问题讨论】:

  • 那个 HTML-component 让我很困惑,它是你的 HTML-page 中的一行吗?
  • 从示例中并不清楚问题是什么,但是我想说 JS 远非用于创建常见包含的理想方法。改为在服务器端进行。
  • 因为你的元素 $('span.test') 不存在
  • 我已经编辑了示例以使其更清晰
  • 我测试了你的代码,效果很好jsfiddle.net/xrenaz32/2

标签: jquery html include


【解决方案1】:

这是因为“main.js”在“intro-text.html”之前加载,这意味着main.js在寻找时

$('span.intro-text')

这不返回任何内容,这意味着您没有隐藏任何内容,然后当加载 intro-text.html 时,它只会显示该跨度。为了防止这种情况,您必须在加载 intro-text.html 后加载 main.js。

<div id="include-introText"></div>

<script type="text/javascript">

  $('#include-introText').load('intro-text.html', function () {
     var script = document.createElement('script');
     script.onload = function () {
        //do stuff with the script
     };
     script.src = "main.js";

    document.head.appendChild(script);
  });

</script>  

【讨论】:

  • 啊,是的,我认为这就是原因,但我找不到修复它。这行得通,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-19
  • 2014-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 2018-07-17
相关资源
最近更新 更多