我尝试jquery教程,但它没有给出预期的输出

时间:2014-08-09 08:05:13

标签: javascript jquery html

当用户点击显示的文字时,此程序会弹出警告信息,然后将文字设为大写。

<script src="jquery-min.js"></script>
<script>
   //run once the page is loaded
   jquery(document).ready(function ($) {
       //Attach a click event to the span element
       $('#test_span').click(function () {
          //Read the elemnt's current value
          var elemnt_text = $('#test_span').html();
          //display the curretn value of this span
          alert(element_text);
          //convert the value to upper case
          element_text = element_text.toUpperCase();
          //change the span to this new value
          $('#test_span').html(element_text);
       });
  });
</script>
</head>
<span id='test_span'>Testing jQuery</span>

4 个答案:

答案 0 :(得分:5)

试试这个, elemnt_text 拼写不正确。使用 element_text

要获取元素的文字内容,请使用 .text() 代替.html()

var element_text = $('#test_span').text();

而不是

 var elemnt_text = $('#test_span').html();

演示: http://jsfiddle.net/rk72eu8m/

Difference between jQuery text() and html() functions

答案 1 :(得分:0)

你有拼写错误。试试这个

 <script src="jquery-min.js"></script>
    <script>
        //run once the page is loaded
        $(document).ready(function () {
            //Attach a click event to the span element
            $('#test_span').click(function () {

                //Read the elemnt's current value

                var element_text = $('#test_span').html();

                //display the curretn value of this span
                alert(element_text);

                //convert the value to upper case
                element_text = element_text.toUpperCase();

                //change the span to this new value
                $('#test_span').html(element_text);
            });
        });
</script>
    </head>

        <span id='test_span'>Testing jQuery</span>   
希望它有所帮助。

答案 2 :(得分:0)

错字:

var elemnt_text = $('#test_span').html();

您的变量拼写错误。它应该是element_text

它应该与纠正一起使用。

答案 3 :(得分:0)

将您的代码更改为此 demo

var elemnt = $('#test_span');

//Attach a click event to the span element
elemnt.click(function () {

    //Read the elemnt's current value
    var element_text = elemnt.text();

    //display the curretn value of this span
    alert(element_text);

    //convert the value to upper case
    element_text = element_text.toUpperCase();

    //change the span to this new value
    $('#test_span').html(element_text);
});