javascript - 将内联 Javascript 转换为 onclick 事件

标签 javascript jquery html ajax

我会直言不讳。我的大部分技能都是纯 HTML 和 CSS。我正在越来越多地尝试扩展到 JavaScript 和 JQuery 并拥有一些经验,足以理解许多简单的教程并通过我自己的更改来实现它们,但如果没有备忘单或类似的示例,我自己做很多事情还不够从。无论如何:

我想尝试THIS教程中我发现使用 Ajax 来替换 div 的内容,但实现需要较差的标记(内联 JS)。他没有建议使用 onclick 事件的方法,我更喜欢这种方式而不是内联 JS。

这是他提供的“Ajax 引擎”,我选择导入/链接它,因为我觉得将所有内容转储到 HTML 中是愚蠢的:

<script type="text/javascript">
// Version 1.1 of May 16, 2013
function RequestContent(url,id) {
var http;
if (window.XMLHttpRequest) {
   try { http = new XMLHttpRequest(); }
   catch(e) {}
   } 
else if (window.ActiveXObject) {
   try { http = new ActiveXObject("Msxml2.XMLHTTP"); }
   catch(e) {
      try { http = new ActiveXObject("Microsoft.XMLHTTP"); } 
      catch(e) {}
      }
   }
if(! http) {
   alert('\n\nSorry, unable to open a connection to the server.');
   return false;
   }
http.onreadystatechange = function() { PublishContent(http,id); };
http.open('GET',url,true);
http.send('');
}

function PublishContent(content,id) {
try {
   if (content.readyState == 4) {
      if(content.status == 200) { document.getElementById(id).innerHTML=content.responseText; }
      else { alert('\n\nContent request error, status code:\n'+content.status+' '+content.statusText); }
      }
   }
catch(error) { alert('Error: '+error.name+' -- '+error.message); }
}
</script>

为了使用RequestContent函数,他只提供了plop内联JS的选项,如下所示:

<ul>
<li>
<a href="javascript:RequestContent('/library/ajaxcontent1.html','fill-me3')">
Click here</a> to fill the div below with the Master Form .PHP logo.
</li>
<li>
<a href="javascript:RequestContent('/library/ajaxcontent2.html','fill-me3')">
Click here</a> to fill the div below with the Master Form V4 logo.
</li>
<li>
<a href="javascript:RequestContent('/library/ajaxcontent3.html','fill-me3')">
Click here</a> to fill the div below with the Most Popular logo.
</li>
</ul>

我了解内联 JS 的工作原理,只是不确定如何编写它以允许 onclick 事件。

我该如何转换内联 JS?我非常感谢您的帮助。

最佳答案

只需将 href 更改为 onclick,并删除 javascript:

<ul>
  <li>
    <a onclick="RequestContent('/library/ajaxcontent1.html','fill-me3')">
Click here</a> to fill the div below with the Master Form .PHP logo.
  </li>
  <li>
    <a onclick="RequestContent('/library/ajaxcontent2.html','fill-me3')">
Click here</a> to fill the div below with the Master Form V4 logo.
  </li>
  <li>
    <a onclick="RequestContent('/library/ajaxcontent3.html','fill-me3')">
Click here</a> to fill the div below with the Most Popular logo.
  </li>
</ul>

关于javascript - 将内联 Javascript 转换为 onclick 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34819289/

相关文章:

javascript - 在 testcafé test 中实现一个在浏览器 url 更改时运行的函数

javascript - Angular ng-repeat 将参数传递给 href 链接

javascript - CSS 在滚动时发生变化,但随着滚动速度的变化

javascript - 如何在fabric js中保留图像的位置

javascript - 将 id 值从 href 传递到 bootstrap modal php

javascript - 下拉菜单的关闭列表

html - Bootstrap 4 : Responsive Button with an Icon on the Left

javascript - 容器 div 覆盖其内容

jquery - 为列表中不可点击的图像添加灯箱功能

html - float 子元素 : overflow:hidden or clear:both?