我相信这应该是一个简单的问题,但我仍然在学习,所以这里:
我有一些代码可以在单击时运行函数,将单击元素的ID分配给一个变量,但我不知道如何将"this.id“值传递给命名空间,而不生成全局变量(我认为这很糟糕)。
<script>
fsa = (function() {
function GetTemplateLoc() {
templateId = document.activeElement.id;
alert(templateId + templateId2);
}
return {
GetTemplateLoc: GetTemplateLoc,
}
})();
//call the functions
$(document).on('click', '.template', function () {
fsa.GetTemplateLoc();
});
</script>和带有随机图片的HTML:
<img id="template-1" class="template" src="http://fc02.deviantart.net/fs70/f/2010/028/c/b/cb21eda885b4cc6ee3f549a417770596.png"/>
<img id="template-2" class="template" src="http://fc02.deviantart.net/fs70/f/2010/028/c/b/cb21eda885b4cc6ee3f549a417770596.png"/>发布于 2015-01-06 08:11:04
下列措施将起作用:
var fsa = (function() {
function GetTemplateLoc() {
var templateId = this.id;
alert(templateId);
}
return {
GetTemplateLoc: GetTemplateLoc,
}
})();
//call the functions
$(document).on('click', '.template', fsa.GetTemplateLoc);jQuery通常调用作为事件处理程序传递的函数,并将this设置为与事件关联的DOM对象。
在本例中,它将调用GetTemplateLoc(),并将this设置为任何.template元素,因此您可以在函数中直接使用this,而不需要传递任何参数。
重要提示:总是使用var声明变量。JavaScript没有自动函数--变量的局部变量范围,也就是说,每个没有var声明的变量都是全局的,无论您在哪里声明它。换句话说,忘记var是一个bug。
发布于 2015-01-06 07:43:37
尝试如下:您可以直接使用this.id传递单击元素的id,其中this引用了单击元素的实例。
<script>
fsa = (function() {
function GetTemplateLoc(templateId ) {
//templateId = document.activeElement.id;
alert(templateId + templateId2);
}
return {
GetTemplateLoc: GetTemplateLoc,
}
})();
//call the functions
$(document).on('click', '.template', function () {
fsa.GetTemplateLoc(this.id);
});
</script>发布于 2015-01-06 10:09:34
如果您能够在jQuery函数中使用GetTemplateLoc,您可以这样做:
var fsa = (function() {
function GetTemplateLoc($trigger) {
var templateId = $trigger.attr('id'),
templateId2 = $($trigger.siblings('.template')[0]).attr('id');
alert(templateId + ' ' + templateId2);
}
return {
GetTemplateLoc: GetTemplateLoc,
}
})();
$(document).on('click', '.template', function () {
fsa.GetTemplateLoc($(this));
});您可以将GetTemplateLoc设置为jQuery对象作为参数( $trigger开头的美元符号可用于将其区分为jQuery对象,而不是任何其他数据类型,这是不必要的,但有时可以帮助澄清问题)。
templateId将存储单击图像的ID值,templateId2将存储其他图像ID的值。我还在警报中添加了两个变量之间的空间。
如果不能在jQuery中使用GetTemplateLoc,可以这样做:
var fsa = (function() {
function GetTemplateLoc(trigger) {
var templateId = trigger.id;
var templateId2 = trigger.nextElementSibling == null ? trigger.previousElementSibling.id : trigger.nextElementSibling.id;
alert(templateId + ' ' + templateId2);
}
return {
GetTemplateLoc: GetTemplateLoc,
}
})();这一次,触发事件的.template被传递到GetTemplateLoc,但这次它不是jQuery对象。templateId分配给触发器的ID,然后在三元中分配templateId2。首先,检查nextElementSibling of trigger以确定它是否是null。如果是的话,我们知道trigger是两个.template元素中的第二个。因此,我们可以将templateId2设置为trigger上一个兄弟级的ID。如果trigger的nextElementSibling不是null,那么我们知道trigger是第一个模板,我们用nextElementSibling的ID填充templateId2。这个精确的方法只适用于两个.template,如果需要更多的额外/不同的逻辑,可能会检索所有.template ID,然后循环它们以添加警告消息。希望这会有所帮助。
https://stackoverflow.com/questions/27794166
复制相似问题