如何让我的jQuery before()调用工作?

时间:2014-07-16 19:17:47

标签: javascript jquery html

我尝试在我的HTML文件中使用JavaScript和jQuery,但它无法正常工作。这是我的代码:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <style type="text/css">
      body {white-space: nowrap;}
      h1 {white-space: nowrap;}
    </style>
    <script src="jquery.js"type="text/javascript"></script>
    <title>SolicitueCotizaciones</title>
  </head>
  <body>
    <script>
      function myFunction() {
      $("input[type='button'][value='Agregar Pieza']").before("<p>new text</p>")};
    </script>


    <br/> Descripcion:
    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
    &nbsp; &nbsp; &nbsp;
    <br/>

    <textarea id="improve" rows="3" cols="20"></textarea>

    </p>
    <div class="divider"/>
    <div style="align-items:left"></div>
    <p>
    </p>
    <p>
      <input type="button" value="+Agregar Pieza" onclick="myFunction()">
    </p>


  </body>
</html>

我还尝试从教程网站中复制代码,但是当我在计算机上运行它们时,它们就会停止工作。任何人都可以帮我弄清楚发生了什么以及我应该怎么做才能解决它?

编辑:我想要实现的是在“+ agregar pieza”按钮上方添加新文本,并在按下“+ agregar pieza”按钮后在标有“descripcion”的文本输入框下方添加新文本,但这绝不会发生。我已经尝试了评论中发布的更正,我编辑了上面的代码以包含它们。但是,在此编辑中,它仍然无法正常工作。我想使用jquery中的.before命令来实现所需的结果,但是如果有更好的方法可以做到这一点,我想知道。

2 个答案:

答案 0 :(得分:5)

首先,jQuery不是您的浏览器的原生,您需要在使用它之前加载它。这些教程应该可以帮到你。

其次,你的代码不正确,应该更接近这个:

$("input[type='button'][value='Agregar Pieza']").before("<p>new text</p>");

现场演示:http://jsfiddle.net/wKhap/

答案 1 :(得分:1)

它不起作用,因为您需要在使用之前导入jQuery。为此,您需要添加此标记:

<script src="http://code.jquery.com/jquery-latest.min.js"
        type="text/javascript"></script>

之前添加对使用jQuery的脚本的任何其他引用。