开发者

Jquery Dom and functions in html body

I have <script>...</script> before my closing body tag here i have the usual

$(function() {
   function test(){
      alert("test");
   }
});

in my html i have input tags <input开发者_如何学Python type="text" onchange="test()" />

I get an error of that test is undefined. I am trying to make IE7 call function onchange I had a whole solution working but since IE7 does not like .change() i am going to put onchange attributes within the inputs but now i have this issue.

Any idea how I can solve this?


test is unknown because it is local to the anonymous function (the ready handler) and not exposed to the outside world. That function is simply a ready handler that gets called when the DOM of the page is ready. If you want to expose test you need to do something like this:

var eventHandlers = $(function() {
   function test() {
      alert("test");
   }

   return {test: test};
})();

This is a bit of overkill and only necessary if you are using the module pattern and using encapsulation. You can now use eventHandlers.test(). If encapsulation is not an issue, I recommend binding to jQuery within the ready handler:

jQuery(document).ready(function(){
    jQuery("#myInput").bind("change", function() {
      alert("test");
    });
});

You can also simply define the function as:

function test() {
  alert("test");
}

Which would be the easiest way. However, I recommend not mixing different ways of doing things. If you are using jQuery, stick to doing everything with jQuery.


if you use jquery, use jquery everywhere.

$(document).ready(function(){

$('input').bind('change',function(){
alert("hi");
});

});


To use it in this way, you need it outside that scope, use only this, no document.ready wrap:

function test(){
  alert("test");
}

If you wrap it in a document.ready handler, it's only available in that scope, you need to declare the function outside for that. However you can do this completely in jQuery as well, like this:

HTML:

<input type="text" id="myElem" />

jQuery:

$(function() {
  $('#myElem').change(function() {
    alert("test");
  });
});
//or, if you wanted the external function for another reason:
$(function() {
  $('#myElem').change(test);
});
function test(){
  alert("test");
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜