[英]Using getElementById to populate an element on page
Am new with Ajax but I know that you can use getelementbyid to update any element on the page with that id. 是Ajax的新手,但我知道您可以使用getelementbyid更新页面上具有该ID的任何元素。 What I want to know is how do you target a particular element on the page if they all have the same id? 我想知道的是,如果它们都具有相同的ID,您如何定位页面上的特定元素?
<li class="a">something</li><li class="a">something b</li>
How do I target the second li? 我如何定位第二个李? since they both using the same id, i cannot use getelementbyid('a') since this will only update the first element with that id. 因为它们都使用相同的id,所以我不能使用getelementbyid('a'),因为这只会更新带有该id的第一个元素。
This is my ajax script 这是我的ajax脚本
function loadurl(dest) {
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new
ActiveXObject("Microsoft.XMLHttp");
} if(XMLHttpRequestObject) {
XMLHttpRequestObject.open("GET", dest);
XMLHttpRequestObject.onreadystatechange = function() {
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
document.getElementById("a").innerHTML =
XMLHttpRequestObject.responseText;
delete XMLHttpRequestObject;
XMLHttpRequestObject = null;
}
}
XMLHttpRequestObject.send(null);
}
} }
and this is link 这是链接
<a onclick="loadurl('page.php?p=1&id=2')">
Using the same id more than once in an HTML page is invalid HTML. 在HTML页面中多次使用相同的ID是无效的HTML。 If you had used class names instead: 如果您使用了类名:
<li class="a">something</li><li class="a">something b</li>
then you could have used document.getElementsByClassName() to get an array containing all the elements with that class. 那么你可以使用document.getElementsByClassName()来获取一个包含该类所有元素的数组。
To put your response in the second element, use something like this: 要将您的响应放在第二个元素中,请使用以下内容:
document.getElementsByClassName("a")[1].innerHTML = XMLHttpRequestObject.responseText;
or, to put your response in all of the elements with that class name, use something like this: 或者,要将您的响应放在具有该类名的所有元素中,请使用以下内容:
var els = document.getElementsByClassName("a");
for (var i = 0; i < els.length; ++i)
els[i].innerHTML = XMLHttpRequestObject.responseText;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.