jQuery - How to select value by attribute name starts with

后端 未结 4 1940
春和景丽
春和景丽 2020-11-28 15:08

I want to select attribute value by giving attribute name (only starts with) For instance if we have html tag

4条回答
  •  忘掉有多难
    2020-11-28 15:52

    You could do it as a jQuery plugin. I'm not convinced its the right way to go about it but here's an example:

    (function($) {
        $.fn.attrBegins = function(s) {
            var matched = "";
            this.each(function(index) {
                $.each(this.attributes, function( index, attr ) {
                    if(attr.name.indexOf(s)===0){
                       matched =  attr.value
                    }
                });
            });
            return matched;
        };
    })(jQuery);
    
    //example use
    var val = $('div').attrBegins('data-');
    alert(val);
    
    

提交回复
热议问题