【问题标题】:Is it possible to assign two functions on a button? [duplicate]是否可以在一个按钮上分配两个功能? [复制]
【发布时间】:2017-02-12 21:45:16
【问题描述】:

我正在创建一个简单的文字处理器,用户可以在其中输入任何文本到专用文本区域并按下三个按钮,这将使文本变为粗体、斜体和下划线。到目前为止,我已经设法做到了这一点,但是如果再次单击该按钮,它必须撤消更改。

即使我在 onclick 中插入两个函数,我似乎也无法取消粗体。

<script>
	
function myFunctionBold() {
    document.getElementById("demo").style.fontWeight = "bold";
}
function myFunctionUnBold() {
    document.getElementById("demo").style.fontWeight = "normal";
}
function myFunctionItalic() {
    document.getElementById("demo").style.fontStyle = "italic";
}
function myFunctionUnderline() {
    document.getElementById("demo").style.textDecoration = "underline";
}
</script>
<style>
.buttonsBold {
      height: 21px;
	  cursor: pointer;
	  display:inline-block;
	  margin: 5px 4px;
      font-weight: bolder;
}
.buttonsItalic {
      height: 21px;
	  cursor: pointer;
	  display:inline-block;
	  margin: 5px 4px;
	  font-style: italic;
}
.buttonsUnderline {
      height: 21px;
	  cursor: pointer;
	  display:inline-block;
	  margin: 5px 4px;
	  text-decoration: underline;
}
</style>
<body>
<p>This is a simple word processor.<br>
Type some text in the text area and press the buttons!
</p>
<form action="textarea"> 
Enter text here:<br>
<input id="demo" type="text" name="yourText">
</form>
<br>

<button class="buttonsBold" onclick="myFunctionBold(); myFunctionUnBold();" >Bold</p>
<button class="buttonsItalic" onclick="myFunctionItalic()">Italic</p>
<button class="buttonsUnderline" onclick="myFunctionUnderline()">Underline</p>
</body>
</html>

【问题讨论】:

  • 只是测试它...
  • 没有。只能分配一项功能。该函数应该切换效果(检查应用了哪个效果,然后应用另一个)。
  • 是的,你可以。根据您帖子中的代码,应该调用 myFunctionBold() 和 myFunctionUnBold() (当然这不是实现您想要做的事情的正确方法)。但为什么是 而不是 ?

标签: javascript html css


【解决方案1】:

您通常应该避免使用内联 javascript。更简洁的方法是使用单独的脚本和addEventListener(),这样您就可以轻松地分配任意数量的函数:

var btn = document.getElementById('btn');

btn.addEventListener('click', doThis);
btn.addEventListener('click', doThat);

function doThis() {
   alert("done this");
}

function doThat () {
  alert("done that");
}
&lt;button id="btn"&gt;Click&lt;/button&gt;

【讨论】:

    【解决方案2】:

    你不需要在点击时调用两个函数,你可以将它逻辑连接到一个函数中,

    function toggleBold() {
        if(document.getElementById("demo").style.fontWeight == "bold"){
            document.getElementById("demo").style.fontWeight = "normal"
        }else{
        document.getElementById("demo").style.fontWeight = "bold"
        }
    }
    

    此功能将切换粗体。

    演示:https://jsfiddle.net/nvujtne7/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-17
      • 2021-06-30
      • 2013-09-17
      • 1970-01-01
      • 2021-07-15
      • 2015-10-20
      • 1970-01-01
      相关资源
      最近更新 更多