Javascript 对象的触发函数
Javascript fire function from object
我想从“对象”在 svg
上添加路径。
myPath()
属性 d
工作正常,但是
我想从对象 obj
触发我的函数,而 d
的 obj.action()
不起作用...为什么?
var obj = {
action: function() {
myPath();
}
}
function myPath() {
return "M 10 10 L 50 10 L 50 90 L 10 90 Z";
}
$("button").on('click', function() {
// doesn't work... :-(
$("svg").find("path").attr("d", obj.action());
// ... but it's working with this :
//$("svg").find("path").attr("d", myPath());
});
svg {
width: 100px;
height: 100px;
background-color: #C0C0C0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Click Me</button>
<svg><path /></svg>
已解决:
var obj = {
action : function() { return myPath() }
// action : myPath //other solution
// action : () => myPath() //other solution
}
function myPath() {
return "M 10 10 L 50 10 L 50 90 L 10 90 Z";
}
$("button").on('click', function() {
$("svg").find("path").attr("d", obj.action());
});
我想从“对象”在 svg
上添加路径。
myPath()
属性 d
工作正常,但是
我想从对象 obj
触发我的函数,而 d
的 obj.action()
不起作用...为什么?
var obj = {
action: function() {
myPath();
}
}
function myPath() {
return "M 10 10 L 50 10 L 50 90 L 10 90 Z";
}
$("button").on('click', function() {
// doesn't work... :-(
$("svg").find("path").attr("d", obj.action());
// ... but it's working with this :
//$("svg").find("path").attr("d", myPath());
});
svg {
width: 100px;
height: 100px;
background-color: #C0C0C0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Click Me</button>
<svg><path /></svg>
已解决:
var obj = {
action : function() { return myPath() }
// action : myPath //other solution
// action : () => myPath() //other solution
}
function myPath() {
return "M 10 10 L 50 10 L 50 90 L 10 90 Z";
}
$("button").on('click', function() {
$("svg").find("path").attr("d", obj.action());
});