Using jQuery's plugin architecture, I have in my js file a line of code that appends a simple "div" element to a textbox. The task seems so simple, but I can't figure out where I'm going wrong.
A snippet from my html file
<div style="margin-top:50px">
Search: <input id="searchbox" type="text" /><br />
</div>
...
开发者_Python百科<script type="text/javascript">
$(document).ready(function() {
$('#searchbox').testplugin();
})
</script>
This is from the testplugin.js file
init : function(options)
{
// some initialization
// iterate through all the jquery objects
return this.each(function() {
$(this).append('<div>Sample Text</div>');
});
}
At this point, I'm sure that $(this) refers to the correct object (I've tried alerting the id). Also, when I try to do a "view source" in Firefox, I also see the newly-appended div (but not in the actual GUI). However, in Internet Explorer, I am getting an "Unexpected call to method or propery access" error.
What am I doing wrong here? Or what should I do to make this work?
Thanks! Erwin
Erwin, I'm fairly sure that per spec - you cannot put a div element inside of an input element. This is probably the source of your IE error & the reason you do not see anything in your browser when it loads up.
Try doing .val('test'); instead of append() & you'll probably encounter working code, same for .addClass('yourcssclass'); or any other "lawful" DOM operation.
init : function(options)
{
// some initialization
// iterate through all the jquery objects
return this.each(function() {
$(this).val('Sample Text');
});
}
this code will help if you are trying to make the text inside the textbox 'Sample Text'
your plugin will still work on elemets such as div
,a
etc...
Modified my code to use after() instead of append()
init : function(options)
{
// some initialization
// iterate through all the jquery objects
return this.each(function() {
$(this).after('<div>Sample Text</div>');
});
}
精彩评论