2017-04-09 64 views
0

我試圖對多個段落元素使用相同的JavaScript和AJAX代碼。我需要獲取段落的內容(innerHTML),因爲這是我的PHP的輸入參數。但正如你所看到的,代碼依賴於p標籤的id或class名稱。我知道它只適用於一個例子。我如何使它適用於很多示例?下面是代碼 將JS函數應用於多個元素

<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> 

回答

-1

這正是事情的jQuery的類型是專爲。

您可以選擇您的段落對象,然後在其上調用foreach

$('P').each(function() { 
    var innerHTML = $(this).html(); 
    //dostuff 
}); 
0

需要,因爲你已經傳遞Element對象是哪個事件正在發生的事情與

var myElement = obj; 

更換

var myElement = document.getElementsByClassName("demo"); 

0

您可以修改您的函數,以便它將當前元素的innerHTML作爲參數並按如下所示調用它:mOver(this.innerHTML)。

相關問題