I am looking for a jquery plugin that will check the type of element and set its value wither its via html() or val() or text() depending on the element. Is such available? Would be great to have a common plugin to set the value of a html element.
I don't think you'd need a plugin for this, but you could write a quick jQuery extension:
$.fn.set_val = function(value) {
switch ( this[0].nodeName.toLowerCase() ) {
case 'input':
$(this[0]).val(value);
break;
default:
$(this[0]).html(value);
break;
}
};
Then you could call it like this:
<input type="text" name="foo" id="foo" value="" />
<div id="bar"></div>
<script type="text/javascript">
$(document).ready(function() {
$('#foo').set_val('hello');
$('#bar').set_val('goodbye');
});
</script>
You could add more conditions for different HTML elements to the switch statement as needed. http://jsfiddle.net/hans/4T3x5/
精彩评论