从DOM中获取价值并将其添加到按钮值

时间:2019-10-21 09:05:38

标签: javascript

我有一个比较复杂的问题,95%可以解决,但是由于不知道js而在最后一步:(用PHP编写了我的整个代码,但是聪明的框架不允许我运行它(当然出于安全原因)-问题是在我的网站上获取EAN代码(在单独的数据库中搜索)并在模式弹出窗口中回显结果。

一切正常,除了我不知道如何搜索并最终将该值添加到按钮以启动该过程...

这是头脑中的js

function showthestock(str) {
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
  } else {
    // code for IE6, IE5
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("showithere").innerHTML = this.responseText;
    }
  };
  xmlhttp.open("GET", "searchresult.php?q=" + str, true);
  xmlhttp.send();
}

和HTML按钮等。

<button id="myBtn" type="button" class="btn btn-danger" data-toggle="modal" data-target="#myModal" value="1234567890123" onclick="showthestock(this.value)">stock in our shop...</button>

.....
模态弹出窗口等... ....     

例如,我需要页面中的EAN代码是

<div class="product-reference">
  <label class="label">EAN </label>
  <span itemprop="sku">065541068780</span>
</div>      

该代码与在按钮中手动添加的EAN代码一起使用时效果很好,但是我不知道如何从站点窃取EAN并将其自动添加到按钮的值中...

请告知

3 个答案:

答案 0 :(得分:0)

每页只有一个EAN吗? 如果是这样,请给您的跨度提供一个ID。

<span itemprop="sku" id="ean">065541068780</span>

然后做

var ean = document.getElementById("ean").innerHTML;

document.getElementById("myBtn").value = ean;

如果您无法修改HTML,则可以尝试使用正则表达式隔离EAN:

var regex = new RegExp(/<span itemprop="sku">([^<]*)<\/span>/gi);
var matches = regex.exec(document.body.innerHTML);

var myEAN = matches[1];

答案 1 :(得分:0)

尝试一下:

document.getElementById("myBtn").addEventListener("click", function(){
var parent = document.querySelector('div.product-reference');
var child = parent.querySelector('span[itemprop="sku"]').innerHTML;
document.getElementById('myBtn').value = child;
});

找到product-reference,然后在这里得到span并带有EAN号。接下来将此值设置为button。 希望有帮助

答案 2 :(得分:0)

感谢Mike和Mosquito的好主意,终于使它像魅力一样发挥作用。

相关问题