我有外部js,它在我的HTML中的一个div中被调用。 在该外部文件中,我有以下代码:
var script = document.createElement("script");
script.innerHTML = '$("body").prepend(\'<input type="hidden" id="sid" value="0">\');var vl=0;$(".sbut").click(function(){vl ++; var snew=vl;$("#sid").val(snew).trigger("change");});';
document.head.appendChild(script);
$("#sid").change(function(){
alert("change");
});
未触发警报。如果我试试这个:
var script = document.createElement("script");
script.innerHTML = '$("body").prepend(\'<input type="hidden" id="sid" value="0">\');var vl=0;$(".sbut").click(function(){vl ++; var snew=vl;$("#sid").val(snew).trigger("change");});$("#sid").change(function(){somef();alert("change");}); ';
document.head.appendChild(script);
function somef(){
alert("change");
}
我得到的是我的函数somef未定义。我猜这必须做我的功能顺序,但我不确定究竟是什么。有人可以建议我这样做的正确方法是什么?此外,我的外部脚本(fscript.js)在HTML中的一个div中被调用,我无法更改它,因为我无法访问HTML。这就是为什么我也附加输入和脚本。
答案 0 :(得分:0)
您正在动态添加sid
元素,因此在绑定更改事件处理程序时它不可用,请尝试下面的代码来绑定事件处理程序
$(document).on("change","#sid",function(){
alert("change");
});
答案 1 :(得分:0)
正如我在评论中提到的,我没有看到将脚本编写为字符串并将其作为脚本标记注入的理由。 fscript.js
已经被加载,所以你可以在其中编写代码,它将在与页面中的脚本标记相同的上下文中运行。
这就是我写它的方式。
// Use an IIFE to encapsulate our code so our variables don't leak into
// the global namespace. This will ensure they don't collide with
// and existing JS in the page avoiding creating bugs in both our code
// and the surrounding page
(function () {
'use strict';
var vl = 0,
// create the sid element and store a reference to the
// returned jQuery object in a variable we can use to
// refer to it later
sid = $('<input type="hidden" id="sid" value="0">');
// attach the change event to sid
sid.change(function() {
alert('Change, sid is now ' + sid.val());
});
// inject sid into the DOM
$('body').prepend(sid);
// use event delegation to add the click event for .sbut
// this will ensure that any .sbut elements in the HTML
// after this script is run will have the click handler
// If you know that .sbut will always appear above the place
// where your script runs, you could just use a normal
// jQuery selector instead.
$(document).on('click', '.sbut', function() {
vl++;
// there doesn't seem to be any need to create the
// snew var here, its value is exactly the same as vl
// at this point, just use vl
sid.val(vl).trigger('change');
});
}());
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="sbut">.sbut</button>
&#13;
我使用Immediately-Invoked Function Expression (IIFE) 包装代码以封装它,以便它不会干扰页面上的其他代码 反之亦然。使用strict mode也是一种很好的做法, 它可以帮助避免一些常见类型的错误并执行一些最佳实践。
我使用event delegation将点击事件附加到.sbut
因为我不知道在您的脚本加载后是否出现任何.sbut
元素,似乎可能是案件。如果您知道在加载脚本之前始终会发生.sbut
,则可以将其更改为正常的$('.sbut').click(function() {});
处理程序。