将此简单的javascript转换为jquery

时间:2018-07-13 14:33:12

标签: jquery

    <!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <p id="text">Javascript is -</p>
    <button id="firstpara">Click Me</button>
    <script type="text/javascript">
        document.getElementById("firstpara").onclick = function() {
            document.getElementById("text").innerHTML = "I THINK " + document.getElementById("text").innerHTML + " awesome";
        }
    </script>
</body>
</html>

https://jsfiddle.net/xpvt214o/411211/

当单击按钮时,代码会在“ javascript is”之前添加“ I think”,并在“ JavaScript”之后添加“ awesome”。

这不能按预期工作,它补充说,我认为“文本Javascript”很棒之后

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <p id="text">Javascript is -</p>
    <button id="firstpara">Click Me</button>
    <p id="empty"></p>
    <button id="createText">Create Text</button>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <script type="text/javascript">
            $("#firstpara").click(function() {
                $("#text").append("I think ") + $("#text").html() + $("#text").append(" is awesome");
            });
    </script>
</body>

1 个答案:

答案 0 :(得分:2)

其字面翻译是将字符串连接在一起。请注意,您不需要append(),它的另一含义与此逻辑无关。而是像这样使用html()

$("#firstpara").click(function() {
  $("#text").html("I think " + $("#text").html() + " is awesome");
});
<p id="text">Javascript is -</p>
<button id="firstpara">Click Me</button>
<p id="empty"></p>
<button id="createText">Create Text</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

或者,您可以为html()提供一个函数,该函数接收当前值作为参数。这样会更高效,因为它意味着您无需两次选择#text元素:

$("#firstpara").click(function() {
  $("#text").html(function(i, h) {
    return "I think " + h + " is awesome";
  });
});
<p id="text">Javascript is -</p>
<button id="firstpara">Click Me</button>
<p id="empty"></p>
<button id="createText">Create Text</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>