Javascript 在iframe中加载url并添加类

Javascript 在iframe中加载url并添加类,javascript,php,jquery,html,iframe,Javascript,Php,Jquery,Html,Iframe,我的情况与此非常相似: 我需要做的是:当我在栏中输入一个新的url并按GO键时,iframe应该被赋予一个类 我试过了 $( "button" ).click(function() { $("iframe").addClass("new-class") }); 但是整个页面被重新加载,我丢失了新添加的类。还有别的办法吗 我的页面在php中,html如下 <?php $src = (empty($_GET['url'])) ? 'http://css-tricks.com/' : ad

我的情况与此非常相似:

我需要做的是:当我在栏中输入一个新的url并按GO键时,
iframe
应该被赋予一个类

我试过了

$( "button" ).click(function() {
  $("iframe").addClass("new-class")
});
但是整个页面被重新加载,我丢失了新添加的类。还有别的办法吗

我的页面在
php
中,html如下

<?php $src = (empty($_GET['url'])) ? 'http://css-tricks.com/' : addslashes(filter_input(INPUT_GET, 'url', FILTER_SANITIZE_URL));?>
    <header class="header">
        <form method="get" action="" id="url-form">
            <label for="url" id="url-toggle" class="url-toggle">URL</label>
             <input id="url" type="text" name="url" placeholder="Enter any URL" value="<?php echo $src; ?>" />
             <button id="url-submit">Go</button>
          </form>
    </header>

    <iframe id="sg-viewport" src="<?php echo $src; ?>" sandbox="allow-same-origin allow-scripts allow-forms"></iframe>

    <footer class="footer">
        footer
    </footer>

统一资源定位地址

您应该拦截表单提交。试试这个:

$("#url-form").submit(function(e) {
    e.preventDefault();
    $("iframe").addClass("new-class");
});

iframe正在重置。但是,您可以通过针对iframe的内容来获得所需的内容


$(“iframe”).contents().find(“#chosenElement”).addClass(“myClass”)

这是可行的,但它只是添加了类,防止实际加载URLthis
jQuery(window.load(function(){$(“iframe”).contents().find(“body”).addClass(“myClass”);}
但它不起作用:/ok,那么告诉我你想要实现什么,应该发生什么?@Romko我进入页面。我插入一个我选择的url,单击按钮,结果刷新的iframe添加了一个类