简体   繁体   中英

jquery - checking for inline javascript on attribute

Is there a way to test if a custom attribute is a function? I've tried using jquery's isFunction method, but it doesn't seem to work with this scenario.

For example:

<input id="test" class='date' oncomplete="function() { alert('i am a function'); }" type="text" />

<script>
    $(".date").livequery(function () {
        var onComplete = $(this).attr("oncomplete");
        if ($.isFunction(onComplete)) {
            $(this).mask("99/99/9999", { completed: onComplete });
        } else {
            $(this).mask("99/99/9999");
        }
    });
</script>

I have several date fields. I'm trying to give a couple of them special behavior. I know I can just have a separate jquery selector to set them up with the behavior they need. But wanted to see if there was an inline way of doing this.

You will have to use eval() for this; inline JS in an attribute is just a plain string.

I'd highly suggest you to not use inline JS at all - it's not nice to read and even harder to maintain/debug.

When getting attributes from DOM elements, jQuery converts them to functions if they are DOM events (like onclick , onkeyup , etc.), but not if they are custom "events" (example: http://jsfiddle.net/FJWhp/1/ ).

I suggest NOT doing it this way. I suggest putting the function in your JavaScript, and use a data- attribute to store its name.

Like this:

<input id="test" class='date' data-complete="dateComplete" type="text" />

<script>
    function dateComplete() {
      alert('i am a function'); 
    }

    $(".date").livequery(function () {
        var onComplete = $(this).data("complete");
        if ($.isFunction(window[onComplete])) {
            $(this).mask("99/99/9999", { completed: window[onComplete] });
        } else {
            $(this).mask("99/99/9999");
        }
</script>

Or better yet, just have the function in JavaScript and don't attach it to the DOM element at all.

<input id="test" class='date' type="text" />

<script>
    $(".date").livequery(function () {
        $(this).mask("99/99/9999", {
            completed: function(){
              alert('i am a function');
            }
        });
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM