外部JS函数无法识别

时间:2017-08-17 02:29:55

标签: javascript jquery html

我在一个名为modal.html的文件中创建一个模态,并且填充模态的内容来自外部JS文件。

内容是以下函数在名为one.js的JS文件中返回的字符串:

function current()
{
  if(selection === 0 && yesResources[questionsCounter] != null)
  {
    return yesResources[questionsCounter];
  }
  else if(selection === 1 && noResources[questionsCounter] != null)
  {
  return noResources[questionsCounter];
  }
  else
  {
    return 'You are on the right track!';
  }
}

为模态编写的HTML代码如下:

<!-- The Modal -->
<div id="myModal" class="modal">

    <!-- Modal content -->
    <div class="modal-content">
        <div class="modal-header">
           <span class="close">&times;</span>
           <h2>Resources</h2>
        </div>
    <div class="modal-body">
        <p>Test</p>
        <p id='modalContent'></p>
    </div>
    <div class="modal-footer">
        <h3>Living Progress</h3>
    </div>
  </div>
</div>

我想调用current()函数用id&#39; modalContent&#39;填充段落空间。我尝试过使用

document.getElementById("modalContent").innerHTML = current(), 
document.getElementById("modalContent").textContent = current(), 

调用段落标签之间的功能等。

我检查了页面的控制台,并且没有定义current(),这意味着它没有从JS中提取。我怎样才能解决这个问题?我有一种感觉,我必须写一个回调函数,但我不知道我会怎么做。

增量问题记者:

// Click handler for the 'next' button
$('#next').on('click', function (e)
{
e.preventDefault();
findNextPrinciple();

// Suspend click listener during fade animation
if(resources.is(':animated'))
{
  return false;
}
choose();
findNextPrinciple();

// If no user selection, progress is stopped
if (isNaN(selection))
{
  alert('Please make a selection!');
}
else
{
  questionsCounter++;
  displayNext();
  findNextPrinciple();
}
if(questionsCounter === tracks[track].questions.length)
  {
$('#next').hide();
$('#prev').hide();
$('#start').hide();
provideResources();
displayResources();
  }
});

// Click handler for the 'Start Over' button
$('#start').on('click', function (e) {
e.preventDefault();

if(resources.is(':animated'))
{
  return false;
}
questionsCounter = 0;
selection = 0;
displayNext();
$('#start').hide();
});

&#13;
&#13;
(function()
{
  var tracks = [
  {
    questions: ['Is the leadership in the business committed to privacy?', 'Do you know what personal information is collected by the business?',
    	'Do you know where personal information is stored or kept?', 'Does the business have personal information that it no longer needs or uses?',
    	'When the business is considering the introduction of new IT systems, programs, applications or business processes, is privacy explicitly considered in the documentation?',
    	'When the business needs to find a solution involving personal information, is there a process for considering privacy along with other business objectives?',
    	'Does the business protect personal information from loss, theft, unauthorized alteration?', 'Does the business adequately protect the devices in which personal information is stored?',
    	'Do the individuals from whom you collect personal information know how the business uses and protects their information?',
    	'When the business collects or handles personal information, do staff keep the interests of the individuals to whom the information relates?'],
  },
  {
    questions: ['Is the leadership in the business committed to privacy?', 'Has the business assigned an individual who has responsibility for privacy?',
    	'Do you know what personal information is collected by the business?', 'Do you know where personal information is stored or kept?',
    	'Does the business have a process to deal with a privacy breach?', 'Is there a privacy training program for staff?',
    	'When the business collects personal information, do you know the reason for collecting it?', 'Does the business have personal information that it no longer needs or uses?',
    	'Are only those staff who need the personal information for their work given access to it?', 'When the business is considering the introduction of new IT systems, programs, applications or business processes, is privacy explicitly considered in the documentation?',
    	'When the business needs to find a solution involving personal information, is there a process for considering privacy along with other business objectives?',
    	'Does the business protect personal information from loss, theft, unauthorized alteration?', 'Does the business adequately protect the devices in which personal information is stored?',
    	'Do the individuals from whom you collect personal information know how the business uses and protects their information?',
    	'When the business collects or handles personal information, do staff keep the interests of the individuals to whom the information relates?'],
  },
  {
    questions: ['Is the leadership in the business committed to privacy?', 'Has the business assigned an individual who has responsibility for privacy?',
    	'Is the role and responsibility for privacy documented?', 'Do you know what personal information is collected by the business?',
    	'Do you know where personal information is stored or kept?', 'Does the business have a process to deal with a privacy breach?',
    	'Is there a privacy training program for staff?', 'When the business collects personal information, do you know the reason for collecting it?',
    	'Does the business have systems and procedural controls to ensure that personal information collected is necessary and NOT optional?',
    	'Is the individual provided the opportunity to give consent if sensitive personal information is collected?',
    	'Is the individual asked for consent if the personal information is used for a new reason?', 'Does the business have personal information that it no longer needs or uses?',
    	'Are only those staff who need the personal information for their work given access to it?', 'When the business is considering the introduction of new IT systems, programs, applications or business processes, is privacy explicitly considered in the documentation?',
    	'When the business needs to find a solution involving personal information, is there a process for considering privacy along with other business objectives?',
    	'Does the business protect personal information from loss, theft, unauthorized alteration?', 'Does the business adequately protect the devices in which personal information is stored?',
    	'Do the individuals from whom you collect personal information know how the business uses and protects their information?',
    	'Do the individuals from whom you collect personal information know who to contact if they have questions about how the business deals with privacy?',
    	'Is there a privacy policy and is it publicly available?', 'Is there a process about how the business will handle complaints from individuals about issues involving their personal information?',
    	'When the business collects or handles personal information, do staff keep the interests of the individuals to whom the information relates?',
    	'Are individuals given a choice to withdraw, opt-out or remove their personal information?',
    	'Is there a way for individuals to access and if necessary, make corrections if their personal information is not accurate?'],
  },
  ];

  var track = 0;
  //Tracks principle number
  var principleCounter = 1;
  //Tracks questions number
  var questionsCounter = 0;
  //Array containing user choices
  var selection = 0;
  //resources div object
  var resources = $('#resources');
  //Choices
  var choices = ['Yes', 'No']
  //Principle descriptions
  var principleTitle = ['', '', '', ''];
  var principleDescriptions = ['', '', '', ''];
  var yesResources2 = ["",
    "",
    "",
    "",
    'Refer to <a href="https://www.ipc.on.ca/wp-content/uploads/Resources/naid.pdf">Best Practices for Secure Destruction of Sensitive Information</a>',
    "",
    "",
    'Refer to <a href="https://www.bdc.ca/en/articles-tools/technology/invest-technology/pages/computer-security-how-protect-your-technology.aspx">Business Development Bank of Canada’s “10 questions to boost your tech security”</a>',
    'Refer to <a href="https://www.bdc.ca/en/articles-tools/technology/invest-technology/pages/computer-security-how-protect-your-technology.aspx">Business Development Bank of Canada’s “10 questions to boost your tech security”</a>',
    "",
    ""];
  var noResources2 = ['Review "Why you need to care about privacy."',
    'Step 5: Create a data map will help you track this information.',
    'Step 5: Create a data map will help you track this information.',
    "",
    'Refer to <a href="https://www.priv.gc.ca/en/privacy-topics/privacy-impact-assessments/02_05_d_59_pia/">Top Ten Dos and Don’ts for Privacy Impact Assessments</a>',
    'Review "Why you need to care about privacy."',
    'Refer to <a href="https://www.bdc.ca/en/articles-tools/technology/invest-technology/pages/computer-security-how-protect-your-technology.aspx">Business Development Bank of Canada’s “10 questions to boost your tech security”</a>',
    'Refer to <a href="https://www.bdc.ca/en/articles-tools/technology/invest-technology/pages/computer-security-how-protect-your-technology.aspx">Business Development Bank of Canada’s “10 questions to boost your tech security”</a>',
    'Refer to the <a href="http://blog.priv.gc.ca/index.php/2013/08/13/initial-results-from-our-internet-privacy-sweep-the-good-the-bad-and-the-ugly/">Federal Privacy Commissioner’s Office “Privacy policies – the good, the bad, the ugly”</a> for examples, <a href="https://ico.org.uk/media/for-organisations/documents/1625136/good-and-bad-examples-of-privacy-notices.pdf">UK’s “Privacy Notices, transparency and control”</a> for examples of good & bad notices, and <a href="https://www.priv.gc.ca/en/about-the-opc/publications/pp_info_201310/">“10 Tips for a Better Online Privacy Policy and Improved Privacy Practice Transparency”</a> if your business has or plans to have a website',
    'Refer to "Additional Resources: Educating Employees", which includes a sample privacy clause for an employee Code of Conduct agreement. Refer to "Additional Resource: Social Media Policy Template" if your organization uses social media'];

  // Display initial questions
  displayNext();

  // Click handler for the 'next' button
  $('#next').on('click', function (e)
  {
    e.preventDefault();
    findNextPrinciple();

    // Suspend click listener during fade animation
    if(resources.is(':animated'))
	{
      return false;
    }
    choose();
    findNextPrinciple();

    // If no user selection, progress is stopped
    if (isNaN(selection))
	{
      alert('Please make a selection!');
    }
    else
	{
      questionsCounter++;
      displayNext();
      findNextPrinciple();
    }
    if(questionsCounter === tracks[track].questions.length)
	  {
  	$('#next').hide();
  	$('#prev').hide();
  	$('#start').hide();
  	provideResources();
  	displayResources();
	  }
  });

  // Animates buttons on hover
  $('.button').on('mouseenter',
  function ()
  {
    $(this).addClass('active');
  });
  $('.button').on('mouseleave',

  function ()
  {
    $(this).removeClass('active');
  });

  // Creates and returns the div that contains the questions and
  // the answer selection
  function createquestionsElement(index)
  {
    var qElement = $('<div>',
	{
      id: 'questions'
    });

    var header = $('<h2>Principle ' + (index) + ' - ' + principleTitle[principleCounter-1] + '</h2>');
    var description = $('<p>' + principleDescriptions[principleCounter-1] + '</p>');
    qElement.append(header);
    qElement.append(description);

    var question = $('<p>').append((questionsCounter+1) + '. ' + tracks[track].questions[questionsCounter]);
    qElement.append(question);

    var radioButtons = createRadios(index);
    qElement.append(radioButtons);

    return qElement;
  }

  // Creates a list of the answer choices as radio inputs
  function createRadios(index)
  {
    var radioList = $('<ul>');
    var item;
    var input = '';
    for (var i = 0; i < choices.length; i++)
	{
      item = $('<li>');
      input = '<input type="radio" name="answer" value=' + i + ' />';
      input += choices[i];
      item.append(input);
      radioList.append(item);
    }
    return radioList;
  }

  // Reads the user selection and pushes the value to an array
  function choose()
  {
    selection = +$('input[name="answer"]:checked').val();
    allSelections[questionsCounter] = selection;
  }

  // Displays next requested element
  function displayNext()
  {
    resources.fadeOut(function()
	{
      $('#questions').remove();
      if(questionsCounter < tracks[track].questions.length)
	  {
        var nextquestions = createquestionsElement(principleCounter);
        resources.append(nextquestions).fadeIn();
        if (!(isNaN(selection)))
		{
          $('input[value='+selection+']').prop('checked', true);
        }

        // Controls display of 'prev' button
        //if(questionsCounter === 1)
		//{
        //  $('#prev').show();
        //}
      if(questionsCounter === 0)
		{
          $('#prev').hide();
          $('#next').show();
        }
      }
      else if(questionsCounter === tracks[track].questions.length)
	  {
        $('#next').hide();
        $('#prev').hide();
        $('#start').hide();
      }
    });
  }

  function findNextPrinciple()
  {
	  if(questionsCounter === tracks[track].nextPrinciple[principleCounter-1])
	     {
	      	principleCounter++;
	     }
  }

  //Return value of current selection
  window.current = function()
  {
	  if(selection === 0 && yesResources2[questionsCounter] != "")
	  {
		return yesResources2[questionsCounter];
	  }
	  else if(selection === 1 && noResources2[questionsCounter] != "")
	  {
	  return noResources2[questionsCounter];
	  }
	  else
	  {
		return questionsCounter;
	  }
  };

    document.addEventListener('DOMContentLoaded', function() {
    document.getElementById("modalContent").innerHTML = current();
    document.getElementById("modalContent").textContent = current();
  });
})();
&#13;
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="ca/en" xml:lang="ca/en" dir="ltr" slick-uniqueid="3">
	<head>
	<style>
/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
    -webkit-animation-name: fadeIn; /* Fade in the background */
    -webkit-animation-duration: 0.4s;
    animation-name: fadeIn;
    animation-duration: 0.4s
}

/* Modal Content */
.modal-content {
    position: fixed;
    bottom: 0;
    background-color: #fefefe;
    width: 100%;
    -webkit-animation-name: slideIn;
    -webkit-animation-duration: 0.4s;
    animation-name: slideIn;
    animation-duration: 0.4s
}

/* The Close Button */
.close {
    color: white;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}

.modal-header {
    padding: 2px 16px;
    background-color: #339966;
    color: white;
}

.modal-body {padding: 2px 16px;}

.modal-footer {
    padding: 2px 16px;
    background-color: #339966;
    color: white;
}

/* Add Animation */
@-webkit-keyframes slideIn {
    from {bottom: -300px; opacity: 0}
    to {bottom: 0; opacity: 1}
}

@keyframes slideIn {
    from {bottom: -300px; opacity: 0}
    to {bottom: 0; opacity: 1}
}

@-webkit-keyframes fadeIn {
    from {opacity: 0}
    to {opacity: 1}
}

@keyframes fadeIn {
    from {opacity: 0}
    to {opacity: 1}
}
</style>

	</head>
	<body>
    	<div id="header" class="header"></div>
        <div class="body-responsive">






<section class="everything-responsive container">
	<div class="lockup">

			

	</div>
</section>

<div class="nav-top-devider"></div>

<div class="sec-nav " data-main="false"> <!--hidden-large-->
    
    </div>
</div>

<section>

    <div class="everything-responsive container events-block-wrapper" id='container'>
	    <div class="content-block">

			<h2></h2>
  			<div id='resources' class="text-left"></div>
		<div class='button' id='next'>
			<a href='#'>Next</a>
		</div>
		<div class='button' id='prev'>
			<a href='#'>Prev</a>
		</div>
		<!-- <div class='button' id='start'> <a href='#'>Start Over</a></div> -->
		<!-- <button class='' id='next'>Next</a></button>
    		<button class='' id='prev'>Prev</a></button>
    		<button class='' id='start'> Start Over</a></button> -->
		</div>
    </div>

	<!-- Trigger/Open The Modal -->
<!--<button id="myBtn" class="button">Resources</button>-->

</section>

<!-- The Modal -->
<div id="myModal" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <div class="modal-header">
      <span class="close">&times;</span>
      <h2>Resources</h2>
    </div>
    <div class="modal-body" id="body">
      <p id='modalContent'></p>
    </div>
    <div class="modal-footer">
      <h3></h3>
    </div>
  </div>
</div>

<script>
// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("next");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal
btn.onclick = function() {
    modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
</script>
<div id="footer" class="footer"></div>

<script src="https://code.jquery.com/jquery.js"></script>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/sticky-nav.extended.js"></script>
<script src="js/magnific-popup.js"></script>
<script src="js/yt-videos.extended.js"></script>
<!--<script src="js/yt-videos.js"></script>-->
<script src="third_party/owl.carousel/owl.carousel.js"></script>
<!--<script src="js/tab-carousel.js"></script>
-->

<script src="https://www.youtube.com/iframe_api"></script>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="js/privacy-toolkit-resources-1.js"></script>


</body>
</html>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

不要依赖隐含的全局功能!始终用全局变量显式:

window.current = function() {
    if (selection === 0 && yesResources[questionsCounter] != null) {
        return yesResources[questionsCounter];
    } else if (selection === 1 && noResources[questionsCounter] != null) {
        return noResources[questionsCounter];
    } else {
        return 'You are on the right track!';
    }
};
document.addEventListener('DOMContentLoaded', function() {
    document.getElementById("modalContent").innerHTML = current();
    document.getElementById("modalContent").textContent = current();
});

显然,您要从示例中删除一些JavaScript,但在调用之前将current定义为window.current 将会有效。

答案 1 :(得分:0)

您可能需要在modal.html文件中尝试此操作。

<script type="text/javascript" src="one.js">

请使用脚本标记开始和结束此操作。

您可以将其放在<body>标签之间。让我知道这个是否奏效。