开发者

Mixing jQuery and JavaScript too much?

Is this valid jQuery? Or have I mixed it up with regular JavaScript too much? In any case it is not working (I would expect it to print "testing" between the appropriate t开发者_高级运维ags):

<script type="text/javascript">
  var testing = "testing";
  testIt=function() {
    $('#cont').html(testing);
  }
</script>

to be invoked when:

<input TYPE="button" NAME="button4" Value="Write" onClick="testIt()">

obviously there is a:

<div id="cont"> </div>

in the html.


No, that's not "mixing jQuery and Javascript" too much. jQuery is Javascript. You won't ever have to worry about mixing them.

I can't reproduce your problem. Your code seems to be working fine. See it in this demo.

That said, I think you should use a method that is more idiomatic to jQuery instead of mixing Javascript with the markup.

I would recommend changing the NAME attribute

NAME="button4"

to an id attribute:

id="button4

and using this jQuery:

var testing = "testing"; 
$("#button4").click(function(){
  $("#cont").html(testing); 
});


  1. JQuery is a javascript library
  2. Your code works properly. The only mistake I could think about is that you didn't include JQuery in your html file.


If you're using jQuery (which is a framework written in/ for JS) anyway, do it in a proper way to improve readability:

var testing = "testing";
$("button[name=button4]").click(function () {
    $("#cont").html(testing);
});

Either put this after the button, or put the code between $(function () { and });. jQuery has an excellent documentation which is available at http://api.jquery.com/


If you are using jQuery, I would recommend using the click handler instead of creating a global variable testIt. For example:

<script type="text/javascript">
    var testing = "testing";
    $("input[name='button4']").click(function() {
        $('#cont').html(testing);
    });
</script>

That provides a nicer separation between your behaviour (javascript) and your content/markup (html).

Technically no, there's no such thing as mixing too much jQuery and javascript (as jQuery is javascript). Since jQuery is an abstraction of a lot of the messy stuff that the DOM does, it would make sense to leverage it where you can rather than writing pure javascript. Writing in as much jQuery as possible also has the benefit that you can worry less about cross-browser differences.


Does your script tag appear before the input element in the page? If not, that's the problem (or at least one of them).

Alternatively check to make sure there aren't any other javascript errors on the page by checking the console in any of the various JS debuggers.

P.S. JQuery is Javascript, more specifically it's a library of helper code written in Javascript to make working with the browser more convenient.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜