如何更改event.target之后的innerHTML元素

时间:2018-02-22 18:25:45

标签: javascript html ajax dom

我做XHR,通过点击p ajax查询,结果应该输出到DOM中的下一个元素,我有很多相同的元素,所以我使用event.target。如何将responsiveText添加到下一个event.target div?

JS代码:

  function loadMoreInfo(e){
var target = e.target;
var serialNumber= target.dataset.serialnumber;
var ajax = new XMLHttpRequest();
var method = "GET";
var url="ajx_php.php/?serial_number=";
ajax.onreadystatechange = function() {
    if (ajax.readyState == 4 && ajax.status == 200) {
        document.getElementById('div-more-info-id').innerHTML = ajax.responseText; //change only one div
    }
}
ajax.open(method, url+serialNumber, true);
ajax.send();}

HTML code:

<p class='p-more-info' id='p-more-info-id' data-serialnumber='$serial_number'>more info     &#9660</p> 
<div class='div-more-info' id='div-more-info-id'> </div>

2 个答案:

答案 0 :(得分:0)

您可以获取<p>标记的id属性,使用正则表达式解析标识符并使​​用它来选择<div>

function loadMoreInfo(e){
    var target = e.target;
    var serialNumber= target.dataset.serialnumber;
    var identifier = target.id.replace(/^p-more-info-(.+)$/, '$1');

    var ajax = new XMLHttpRequest();
    var method = "GET";
    var url="ajx_php.php/?serial_number=";
    ajax.onreadystatechange = function() {
        if (ajax.readyState == 4 && ajax.status == 200) {
            document.getElementById('div-more-info-' + identifier).innerHTML = ajax.responseText;
        }
    }
    ajax.open(method, url+serialNumber, true);
    ajax.send();
}

答案 1 :(得分:0)

link解决了我的问题,谢谢@epascarello