[英]how to set “this” as the child element in onclick event
EDIT 2 : 编辑2 :
Actually, What I was trying to do is passing img properties to server-side, because google app script is javascript in server side. 实际上,我想做的就是将img属性传递到服务器端,因为google app脚本是服务器端的javascript。 And passing data to server can only be as string.
并将数据传递到服务器只能是字符串。 The solution I found is adding a usual img property with value an object containing everything I want (id, src, ... of my img. I JSON.stringified this value and BOOM ... Now I get every data I need.
我发现的解决方案是添加一个通常的img属性,该对象的值包含一个对象,该对象包含我想要的所有内容(img的id,src等)。我通过JSON.stringified这个值和BOOM ...现在获取所需的所有数据。
Thank you for your help and sorry for the misunderstood. 感谢您的帮助,对于误解,我们深表歉意。
EDIT : 编辑 :
Thanks to this thread 多亏了这个线程
https://stackoverflow.com/a/9726264/1859295 https://stackoverflow.com/a/9726264/1859295
I could finally find a solution to my question. 我终于可以找到解决我问题的方法。
I used an .on() method on my ul list and now my "this" is pointing to my img element. 我在ul列表上使用了.on()方法,现在“ this”指向我的img元素。
Original Post: 原始帖子:
I have an empty ul. 我有一个空的ul。 I append li with js.
我用js附加li。 li's contain img with src, id, name attribute AND onclick event which fires a function with "this" as parameter.
li包含具有src,id,名称属性和onclick事件的img,后者会触发以“ this”为参数的函数。 I need my "this" to be the img element within my li.
我需要我的“ this”成为li中的img元素。 Instead, I get my ul as "this"
相反,我的ul为“ this”
my code is: 我的代码是:
function createItemsList(items){
$("#items").empty();
for (var i = 0; i < items.length; i++) {
$("#items").append('<li class="w3-display-container"
id="test"><img src="'+ items[i].url + '" id ="'+ items[i].id +
'" style="height:25px;"
onclick="google.script.run.addItem(this)"; return false;
class="w3-ripple"></li>');
}
};
google.script.run
.withSuccessHandler(createItemsList)
.getItemsList();
There are better ways of creating elements with jQuery: 有使用jQuery创建元素的更好方法:
for (var i = 0; i < items.length; i++) {
let img = $("<img/>", {
src: items[i].url,
id: items[i].id,
css: { height: "25px" },
click: function() { google.script.run.addItem(this); },
"class": "w3-ripple"
});
let li = $("<li/>", {
"class": "w3-display-container"
html: img
});
$("#items").append(li);
}
The $("<tagname/>")
facility accepts a second argument with properties for the new element. $("<tagname/>")
工具接受带有新元素属性的第二个参数。 You can include handler functions with that. 您可以在其中包含处理程序函数。 It's much neater than trying to juggle quote characters in pieced-together HTML via strings.
这比尝试通过字符串混合拼凑在一起的HTML中的引号字符要整洁得多。
I would change the inside for as following 我将内部更改如下
var img = $('<img />').attr('src', items[i].url).attr('id', items[i].id);
img.click(function() {
google.script.run.addItem(this)
})
$("#items").append('<li class="w3-display-container" id="test">').append(img);
Basically to use click eventhandler from jquery so I think this will be img. 基本上使用jquery中的click事件处理程序,所以我认为这将是img。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.