将JS函数应用于多个元素

时间:2017-04-09 09:18:32

标签: javascript php html

我正在尝试为多个段落元素使用相同的JavaScript和AJAX代码。我需要获取段落的内容(innerHTML),因为这是我的PHP的输入参数。但正如您所看到的,代码依赖于p标记的id或类名。我知道它仅适用于一个例子。如何让它适用于许多例子?这是代码          

<style>
#popup-header, #popup-body{
    font-family:Arial;
    font-size:14px;     
    visibility:hidden;
}
#popup-body{
    height:270px;
    width:300px;
    background-color:#CCC;
    padding-left:10px;
    padding-top:10px;
    border-radius:0 0 6px 6px;
}
#popup-header{
    height:30px;
    width:300px;
    padding-left:10px;
    padding-top:10px;
    color:white;
    background-color:#0000CC;
    border-radius;6px 6px 0 0;
}
#popup{
    width:300px;
    height:300px;
    background-color:#CCC
    visibility:hidden;
    border-radius;6px 6px 0 0;

}
</style>
<body>
<script>
function mOut(obj) {
    //obj.innerHTML = myElement.innerHTML; 
    document.getElementById("popup").style.visibility = 'hidden';
    document.getElementById("popup-header").style.visibility = 'hidden';
    document.getElementById("popup-body").style.visibility = 'hidden';
}

function mOver(obj) {
  var myElement = document.getElementsByClassName("demo");
  var xhttp;
  if (window.XMLHttpRequest) {
    // code for modern browsers
    xhttp = new XMLHttpRequest();
    } else {
    // code for IE6, IE5
    xhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("popup").style.visibility = 'visible';
  document.getElementById("popup-header").style.visibility = 'visible';
  document.getElementById("popup-body").style.visibility = 'visible';
  document.getElementById("popup-header").innerHTML =     myElement.innerHTML;
  document.getElementById("popup-body").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "getVerse.php?q="+myElement.innerHTML, true);
  xhttp.send();
}
</script>
<p class="demo" onmouseout="mOut(this)" onmouseover="mOver(this)">Matthew 5:12</p>
<p class="demo" onmouseout="mOut(this)" onmouseover="mOver(this)">Matthew 5:13</p>
<div id="popup">
    <div id="popup-header"></div>
    <div id="popup-body"></div>
</div>
</body>
</html>

3 个答案:

答案 0 :(得分:0)

您需要替换

var myElement = obj;

Element

因为您已经传递了发生事件的Annotation对象。

答案 1 :(得分:0)

你可以修改你的函数,使它将当前元素的innerHTML作为参数,并按如下方式调用它:mOver(this.innerHTML)。

答案 2 :(得分:-2)

这正是jQuery的设计类型。

您可以选择段落对象,然后在其上调用$('P').each(function() { var innerHTML = $(this).html(); //dostuff });

{{1}}