将其简化为一个简单的功能

时间:2017-10-25 17:04:16

标签: javascript

如何将下面的代码键入单个函数以缩短它?

    // Change text
    function changeText(e) 
    {
        document.getElementById(e).innerHTML = "Remove me";
    }
    // Return changed text
    function returnText(e) 
    {
        document.getElementById(e).innerHTML = "App";
    }

    <div onmouseover="changeText('remove')" onmouseout="returnText('remove')"><p id="remove">App</p></div>

2 个答案:

答案 0 :(得分:0)

您应该始终关注single responsibility principle。但是,如果您真的想要合并这两个函数,请执行以下操作:

function changeText(e,text = false)
{
  if(text !== false)
  {
     document.getElementById(e).innerHTML = text;
  }
  else
  {
     document.getElementById(e).innerHTML = "app";
  }
}

//call it like this <div onmouseover="changeText(this,'remove me')" onmouseout="returnText(this)"><p id="remove">App</p></div>

答案 1 :(得分:0)

也许使用箭头函数并使函数更通用:

 Row row = new Row.AddRowBuilder(null, true, 7531436244775314, null, null).SetCells(cells).Build();

现在你可以做到:

const get = id => document.getElementById(id),
           change = (el, text) => el.innerHTML = text, 
           on = (el, evt, handler) => el.addEventListener(evt,handler);

将其应用于事件侦听器(内联js是错误的样式):

change( get("remove"), "App");