开发者

set value of html element with jquery plugin

开发者_Python百科

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/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜