简体   繁体   English

Javascript 抓取一个 html5 数据值用作 var

[英]Javascript grabbbing a html5 data- value to use as a var

So I want to customize the src via js with hidden data but just can't figure out the right flow to write it.所以我想通过带有隐藏数据的 js 自定义 src,但就是想不出正确的流程来编写它。 Looking to grab html5 data- to change the src.希望获取 html5 数据 - 以更改 src。 Any time I have tried to write it can't get it to grab my data- with Var.任何时候我试图写它都无法获取我的数据 - 使用 Var。

referencing question 19320436 for var from data when looking for answers在寻找答案时引用问题 19320436 for var from data

tried尝试过

<html>
<body>

<p id="test" class="customClass" data-newsrc="https://stackoverflow.com"></p>

<script>
var value = $('.customClass').data('newsrc');

document.getElementById("test").innerHTML= '<iframe id="myframe" src=""\>\</iframe>';

document.getElementById("myframe").src= value;
</script>
</body>
</html>

works but is not grabbing a new value from page有效但没有从页面获取新值

<html>
<body>

<p id="test" class="customClass" data-newsrc="https://stackoverflow.com"></p>

<script>

var value = "https://stackoverflow.com/qestions"

document.getElementById("test").innerHTML= '<iframe id="myframe" src=""></iframe>';

document.getElementById("myframe").src= value;
</script>
</body>

First select the #test element, you'll need it more than once.首先是 select #test元素,您将不止一次需要它。 Without using jQuery you can select the data-newsrc property by accessing it from the dataset property.在不使用 jQuery 的情况下,您可以通过从dataset属性访问 select data-newsrc属性。

Instead of writing your HTML in a string, create a new element object with document.createElement , this saves you the step of having to reselect the iframe because you already have a reference.不用将 HTML 写成字符串,而是使用document.createElement创建一个新元素 object,这样就省去了重新选择 iframe 的步骤,因为您已经有了一个引用。

After setting the src ,append the iframe to the test element.srcappend和 iframe 设置为test元素后。

 const test = document.getElementById('test'); const src = test.dataset.newsrc; const iframe = document.createElement('iframe'); iframe.src = src; test.append(iframe);
 <p id="test" class="customClass" data-newsrc="https://stackoverflow.com"></p>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM