我有一个函数来更改我的选择,显示来自php的一些文本。我正在使用 ajax 来执行此请求而无需重新加载整个页面。对我来说的问题是我有一个类有很多div,我想显示ajax与我更改的选择匹配的结果:
<div class="x">
<select class="mySelect">
<option>1</option>
<option>2</option>
</select>
<div class="showHere">php text requested with ajax</div>
</div>
<div class="x">
<select class="mySelect">
<option>1</option>
<option>2</option>
</select>
<div class="showHere">php text requested with ajax</div>
</div>
<div class="x">
<select class="mySelect">
<option>1</option>
<option>2</option>
</select>
<div class="showHere">php text requested with ajax</div>
</div>
ajax 中的行:
document.getElementById("div").innerHTML = xmlhttp.responseText;
我想在div 类"showHere"中显示响应,但在正确的div 中,换句话说,在与我的选择匹配的div 中,我已经更改了,明白了吗?我不知道是否有可能...
或者你可以使用事件的发送者并缩短整个事情。在以下元素中填充 AJAX 调用的结果(这要求div 始终直接位于选择之后)。
使用此代码,您可以获得触发事件的元素(event.srcElement 是用户使用 ie 时无法正确解释 event.target 的后备
):var target = event.target || event.srcElement;
此部分在您选择后选择下一个元素:
var nextDiv = target.nextSibling;
现在添加您的回复:
nextDiv.innerHTML = xmlhttp.responseText;
你肯定需要一些东西来区分div。 可以给他们一个 ID,并将其作为事件中的参数传递给 AJAX 函数。
div class="x">
<select class="mySelect">
<option>1</option>
<option>2</option>
</select>
<div class="showHere" id="first">php text requested with ajax</div>
</div>
<div class="x">
<select class="mySelect">
<option>1</option>
<option>2</option>
</select>
<div class="showHere" id="second">php text requested with ajax</div>
</div>
<div class="x">
<select class="mySelect">
<option>1</option>
<option>2</option>
</select>
<div class="showHere" id="third">php text requested with ajax</div>
</div>
In your script:
function ajaxCall(id_of_target_div) {
...
document.getElementById(id_of_target_div).innerHTML = xmlhttp.responseText ;
}