【问题标题】:Javascript fire function from object来自对象的 Javascript 触发函数
【发布时间】:2022-01-10 16:49:21
【问题描述】:

我想在svg 上添加一条来自“对象”的路径。 myPath() 属性 d 工作正常,但是 我想从对象obj 触发我的函数,而dobj.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>

【问题讨论】:

  • 您的操作没有返回任何内容...action: function() { return myPath() }
  • object = { action: myPath } 可能更简单?
  • action: () =&gt; myPath()
  • @epascarello ...您的解决方案就像一个魅力!这只是语法问题......我花了几个小时在谷歌上到处搜索,并尝试了很多使用括号、括号、花括号等的可能性...... :-) 非常感谢!
  • @evolutionxbox...同样的事情...:-) 非常感谢

标签: javascript jquery object svg path


【解决方案1】:

已解决:

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());
});

【讨论】:

    猜你喜欢
    • 2011-07-13
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 2014-08-12
    • 2014-05-31
    • 1970-01-01
    • 2012-03-02
    • 2019-02-26
    相关资源
    最近更新 更多