使用.load()执行脚本

时间:2013-06-20 15:26:27

标签: php jquery

我在DIV中有一个表单(通常使用“display:none;”隐藏div) 用户打开DIV:onclick='$("#Details").show("slow"); 填写表格并保存数据。

我不希望重新加载整个页面,我只需重新加载此DIV

我试过了:

function(data) {
    $('#Detalils').load(location.href + ' #Detalils');
});

$("#Detalils").load(location.href + " #Detalils, script");

$('#Detalils').load(location.href + ' #Detalils', function() {
$('#script').hide();
})

在#script中我放了我的脚本

在这个div中我有一些脚本,并且由于加载脚本执行时的jQuery,脚本没有被执行。

我无法将脚本放在外部文件中,它必须位于页面主体中。

有没有办法好好执行脚本?

由于

2 个答案:

答案 0 :(得分:0)

您的实际Javascript代码不应该在div中,这就是问题所在。如果您希望重新加载表单以供用户输入新数据,那么在表单中的元素上使用ID,并在其外部或外部文件中编写JQuery代码,这是一个简单的示例:

而非类似:

<form>

    <input type="button" onclick="alert('hello');"> Click me ! </input>

</form>

执行以下操作:

<form>

    <input id="myButton" type="button"> Click me ! </input>

</form>

<script type="text/javascript"> 

    $("#myButton").click(function() 
    {
        alert('hello');
    });

</script>

当然,您必须对代码进行调整,但您没有其他选择。 HTML代码可以随意删除和添加,但Javascript代码不能以相同的方式处理。这有很多原因,但其中一个原因是浏览器只会加载一次Javascript函数,原因很明显。

答案 1 :(得分:0)

我当地环境中的作品。给你一个机会。

HTML:

<div id="wrapper">
<a href="/" id="mremovebtn" title="remove">Remove</a>
<a href="/" id="mreloadbtn" title="reload">Reload</a>
<div id="Details">my details box</div>
</div>

jQuery:

<script type="text/javascript">

function mload() {
/*LOAD IN MY EXTERNAL STUFF*/
    mtarget =  $('#Details'); //the element on your page, that houses your external content
    mscript = 'external.js'; //the js script required for your plugin to work
    mtarget.load("external.html", function(){
    $.getScript(mscript, function() {
        //run the plug-in options code for your external script here
    });
 });
//*/
}

function madjustments() {
/*ADJUST THE LOADING PROCESS*/
    //remove the load request on click from your remove button
    $('#mremovebtn').on("click",function(e) {
      e.preventDefault();
      $('#Details').children().remove();
    });

    //reload the request on click from your reload button
    $('#mreloadbtn').on("click", function(e) {
      e.preventDefault();
      mload();
    });
//*/
}


(function($){
  mload();
  madjustments();
})(jQuery);
</script>

您显然需要2个额外的文件。一个叫做external.html,另一个叫做external.js,我的演示代码可以工作。但是您可以将命名过程更改为适合您的任何内容。

额外: 在外部html文件中设置一个类(在父元素上),例如#external。默认情况下,在样式表中将CSS设置为display:none。然后当页面加载时,只需在jQuery代码中显示()它。

相关问题