jQuery的;代码在HTML页面中不起作用,但在控制台中工作

时间:2018-05-01 05:42:26

标签: jquery html

问题 我正在进行学校演示,但我正在使用jQuery替换.swf动画,但它不起作用。如果将相同的代码复制到我的控制台,它就像一个魅力!有什么帮助吗?

我的代码

<html>
<body>
<div class='div-header'>
  <div class='div-header-title'>Courier Services</div>
</div>
  <div class='div-animation-frame'>
  <h2>A Project By</h2>
  <ul>
    <li>Naqi</li>
    <li>Musa</li>
    <li>Husnain</li>
    <li>Nafey</li>
    <li>Saeed</li>
    <li>Hanzala</li>
  </ul>
  <button class='button-start'>START</button>
</div>

     

$(document).ready(function() {

 var companiesList = ['tcs', 'ocs', 'dhl', 'leopards'];
 var currentIndex = 0;

$('.button-start').on('click', function() {
  $('body').append("<div class='div-next-fab'></div>");
  $('.div-next-fab').append("<i class='fas fa-arrow-right'>");
  $('.div-animation-frame').replaceWith('<div class="div-animation-frame"><embed src="tcs.swf"></div>');
})

// Clicking on the next button will swap the animation file
// Somehow not working
// Copy this to console, hit enter 
// It now works

$('.div-next-fab').on( 'click', function() {
    $('.div-animation-frame').replaceWith("<div class='div-animation-frame'><embed src='ocs.swf'></div>");
})
 });

1 个答案:

答案 0 :(得分:1)

您需要Event binding on dynamically created elements?

更改

$('.div-next-fab').on( 'click', function() {

$(document).on( 'click', '.div-next-fab' function() {

所以你的最终代码应该是

$(document).ready(function() {

 var companiesList = ['tcs', 'ocs', 'dhl', 'leopards'];
 var currentIndex = 0;

$('.button-start').on('click', function() {
  currentIndex = 0;
  $('body').append("<div class='div-next-fab'></div>");
  $('.div-next-fab').append("<i class='fas fa-arrow-right'>");
  $('.div-animation-frame').replaceWith('<div class="div-animation-frame"><embed src="'+ companiesList[currentIndex] +'.swf"></div>');
  currentIndex++;
})

// Clicking on the next button will swap the animation file
// Somehow not working
// Copy this to console, hit enter 
// It now works

$(document).on( 'click', '.div-next-fab' ,function() {
    $('.div-animation-frame').replaceWith("<div class='div-animation-frame'><embed src='"+ companiesList[currentIndex] +".swf'></div>");
    currentIndex = (currentIndex >= companiesList.length - 1) ? 0 : currentIndex + 1;
})
});