简体   繁体   English

jquery - 检查属性上的内联javascript

[英]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. 我已经尝试过使用jquery的isFunction方法,但它似乎不适用于这种情况。

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. 我知道我可以只有一个单独的jquery选择器来设置他们需要的行为。 But wanted to see if there was an inline way of doing this. 但是想知道是否有内联方式来做到这一点。

You will have to use eval() for this; 你必须使用eval() ; inline JS in an attribute is just a plain string. 属性中的内联JS只是一个普通的字符串。

I'd highly suggest you to not use inline JS at all - it's not nice to read and even harder to maintain/debug. 我强烈建议你不要使用内联JS - 阅读起来并不好,甚至更难维护/调试。

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/ ). 从DOM元素获取属性时,jQuery将它们转换为函数(如果它们是DOM事件(如onclickonkeyup等)),但如果它们是自定义“事件”则不会(例如: 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. 我建议将函数放在JavaScript中,并使用data-属性来存储其名称。

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. 或者更好的是,只需在JavaScript中使用该函数,并且根本不将它附加到DOM元素。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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