JavaScript类使用点击处理程序修改段落

时间:2018-09-30 17:56:20

标签: javascript html css

创建一个JavaScript类“ ModifyParagraph”,此处的构造函数接受段落元素。在构造函数中,使用document.createElement创建4个按钮(用于更改段落,粗体,颜色,大小,位置),并在每个按钮上添加click事件处理程序。粗体按钮上的单击处理程序将打开/关闭粗体。

我的代码:

HTML

<!DOCTYPE html>
<html>
    <head>
        <title>Question-2</title>
        <meta charset="UTF-8">
        <script src="q2.js"></script>
        <link rel="stylesheet" href="q2.css" />
    </head>
    <body>
            <div id="myDIV" style="width:500px; ">Lorem ipsum dolor sit amet, porttitor ut donec ut egestas, purus urna consectetuer, arcu et vitae elementum nulla etiam in, sit leo lacus. Ligula cras tortor dignissim laoreet ut, nonummy hendrerit mauris, vitae augue congue congue, vel et augue, eros at. Fringilla id donec libero mauris eleifend. Nulla nunc sit. Consequat sodales placerat faucibus mauris, urna lectus vitae, sit nisl laoreet libero at suscipit ut, neque laoreet dapibus sapien. Sodales sit ut metus commodo tellus, ultricies cursus, et faucibus vitae quam, sit ultrices rhoncus. Massa duis mauris arcu vulputate, iste orci porttitor a ac, quisque venenatis pellentesque in in velit sed, repellat lorem consectetur vero, urna tellus donec. Suscipit in, donec beatae, lectus bibendum morbi justo consectetuer ac, facilisis metus vel non sapien vel. Magna congue vitae quia nulla nulla, lorem enim urna augue et et, sem morbi lorem ornare velit neque morbi, erat id et blandit iaculis.</div>

    </body>

    </ul>
</html>

JavaScript

class ModifyParagraph{
    constructor(myDIV){
        this.myDIV = myDIV;
    function myFunction(){
        var btn = document.createElement("BUTTON");
        var bold = document.getElementById(myDIV);
        btn.addEventListener('click', function(){
            if (bold.style['font-weight']) {
                bold.style.removeProperty('font-weight');
              } else {
                bold.style['font-weight'] = "800";
              }
          }
        }
    }
}

在我的代码中,我在构造函数内部创建按钮并在每个按钮上添加单击处理程序时遇到问题。请让我知道如何进行

2 个答案:

答案 0 :(得分:1)

除了语法错误(我将在后面的答案中解决),您的主要问题是您错过了将创建的button附加到DOM的问题。

这是一个工作示例:

class ModifyParagraph {
  constructor(div) {
    this.myDIV = div;
  }
  toggleBoldStyle() {
    // create the button.
    var btn = document.createElement('button');
    // give it some text/value.
    btn.textContent = 'toggle Bold styling';
    // add click event listener to the button.
    btn.addEventListener('click', function() {
      // if the font-weight is 800 make it 'normal' else if it's other than 800 make it 800'
      // add the 'this' keyword in the addEventListener method references the button, to get the member myDIV we'll just call it without preceding it by 'this'(myDIV in place of this.myDIV).
      myDIV.style.fontWeight = (myDIV.style.fontWeight === '800') ? 'normal':'800';
    });
    // append the button to the DOM
    this.myDIV.appendChild(btn);
  }
}
// testing...
var p = new ModifyParagraph(document.getElementById('myDIV'));
p.toggleBoldStyle();
<div id="myDIV" style="width:500px; ">Lorem ipsum dolor sit amet, porttitor ut donec ut egestas, purus urna consectetuer, arcu et vitae elementum nulla etiam in, sit leo lacus. Ligula cras tortor dignissim laoreet ut, nonummy hendrerit mauris, vitae augue congue congue, vel et augue, eros at. Fringilla id donec libero mauris eleifend. Nulla nunc sit. Consequat sodales placerat faucibus mauris, urna lectus vitae, sit nisl laoreet libero at suscipit ut, neque laoreet dapibus sapien. Sodales sit ut metus commodo tellus, ultricies cursus, et faucibus vitae quam, sit ultrices rhoncus. Massa duis mauris arcu vulputate, iste orci porttitor a ac, quisque venenatis pellentesque in in velit sed, repellat lorem consectetur vero, urna tellus donec. Suscipit in, donec beatae, lectus bibendum morbi justo consectetuer ac, facilisis metus vel non sapien vel. Magna congue vitae quia nulla nulla, lorem enim urna augue et et, sem morbi lorem ornare velit neque morbi, erat id et blandit iaculis.</div>

除了缺少将button附加到DOM之外,您还犯了一些错误:

  • 类方法不需要'function'关键字,您只需编写方法名称即可。
  • 您错过了addEventListener方法的右括号。
  • 为什么要在muyDIV成员中获取刚刚保存的元素。更好的是,您有两种选择:将元素本身发送到构造函数或将其发送到ID,并在对myDIV成员的分配中,通过getElementById方法获取元素。在我的演示中,我将元素本身发送给了构造函数。但是,您可以使事情变得更加复杂,以允许发送ID或元素本身,在构造函数中,您必须检查传入参数的类型。

最后,这是ECMAScript 5类的MDN文档的link

希望我进一步推动了你。

答案 1 :(得分:0)

我的代码, HTML:

SELECT total_users,
       mobile_users / total_users * 100 AS percent_mobile,
       mobile_and_web_users / total_users * 100 AS percent_both
FROM (SELECT COUNT(DISTINCT u.user_id) AS total_users,
             COUNT(DISTINCT m.user_id) AS mobile_users,
             COUNT(DISTINCT w.user_id) AS mobile_and_web_users
      FROM User u
      LEFT JOIN MobileData m ON m.user_id = u.user_id
      LEFT JOIN WebData w ON w.user_id = m.user_id) u

JavaScript

final Optional<Person> checkExistingPerson = checkIt();

checkExistingPerson.ifPresent(person -> {
    State state;
    if("blah".equals(person.getName())) {
        state = State.DUPLICATE;
    } else {
        state = State.NEW;
    }

    return Member(person.getId(), state);
});

return Member(null, State.OK);