简体   繁体   English

如何将 html 属性添加到 (getElementById)

[英]How to add html attribute to (getElementById)

How can I add "src" in iframe attribute ( iframe src=" " ) to getElementById ( document.getElementById(" ").innerHTML = replaceurl )?如何在 iframe 属性 ( iframe src=" " ) 中添加 "src" 到 getElementById ( document.getElementById(" ").innerHTML = replaceurl )?

 <div class="output"> <iframe src="" style="width: 640px; height: 480px;"></iframe> </div> <script> function myFunction() { var geturl = document.getElementById("url").value; var replaceurl = ("https://docs.google.com/gview?url=" + geturl + "&embedded=true"); document.getElementById("").innerHTML = replaceurl; } </script>

You must use the setAttribute method for this ( https://developer.mozilla.org/de/docs/Web/API/Element/setAttribute ).您必须为此使用setAttribute方法( https://developer.mozilla.org/de/docs/Web/API/Element/setAttribute )。

In your case, it can be done by writing the following:在您的情况下,可以通过编写以下代码来完成:

// HTML
<iframe id="your-iframe" src="" style="width: 640px; height: 480px;"></iframe>

// JS
document.getElementById("your-iframe").setAttribute('src', replaceurl);

why not trying to add an id to the iframe element and pass urls to it by calling your function?为什么不尝试向 iframe 元素添加 id 并通过调用 function 将 url 传递给它? like this:像这样:

<div class="output">
        <iframe src="" id="myIframe" style="width: 640px; height: 480px;"></iframe>
    </div>

    <script>
        function myFunction(id) {
          var geturl = document.getElementById("url").value;
          var replaceurl = ("https://docs.google.com/gview?url=" + geturl + "&embedded=true");
          document.getElementById(id).src = replaceurl;
        }
//call your function.
myFunction("myIframe");
    </script>

You can set the src of the <iframe> by directly assigning the new URL to the src property.您可以通过直接将新的 URL 分配给src属性来设置<iframe>src

 function myFunction() { const geturl = document.getElementById("url").value, replaceurl = `https://docs.google.com/gview?url=${geturl}&embedded=true`; document.querySelector('.output iframe').src = replaceurl; } myFunction();
 <input type="text" id="url" value="https://stackoverflow.com/" /> <div class="output"> <iframe style="width: 640px; height: 480px;"></iframe> </div>

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

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