我想创建一个设置按钮的功能 - 这样做我想传递一个自定义目标 - 这可能吗?
function appendHeroButton(parent, child, text, target, x, y, w, h){
var childDiv = $("<div id='"+child+"' class='heroButton noselect' style='left:"+x+"px; top:"+y+"px; width:"+w+"px; height:"+h+"px; position:absolute; background-color:"+action+"; line-height:"+h+"px;'>"+text+"</div>");
$("#"+parent).append(childDiv);
var div = document.getElementById(child);
div.addEventListener('click', target);
}
答案 0 :(得分:1)
如果我已正确理解了这个问题,您希望将回调作为参数添加到appendHeroButton
函数中,并附加到div
。
以下是这样做的示例,您只需按名称引用该功能,然后您可以使用传递的div
与event
进行交互。
function appendHeroButton(parent, child, text, target, x, y, w, h){
var childDiv = $("<div id='"+child+"' class='heroButton noselect' style='left:"+x+"px; top:"+y+"px; width:"+w+"px; height:"+h+"px; position:absolute; background-color:red; line-height:"+h+"px;'>"+text+"</div>");
$("#"+parent).append(childDiv);
var div = document.getElementById(child);
div.addEventListener('click', target);
}
var someFunction = function (e) {
var div = $(e.currentTarget);
console.log(div.text());
};
var parent = "foo";
var child = "bar";
var targetFn = someFunction;
appendHeroButton(parent, child, "text", targetFn, 10, 50, 100, 100);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
<div id="bar">Click here</div>
</div>
&#13;