如何在此JS中使用自定义属性而不是值?

时间:2018-12-05 22:54:54

标签: javascript jquery

例如,我想使用“ test”代替值。我试图找到正确的方法来执行此操作,但是我的方法均无效。值已经用于其他用途。如果您有任何解决方法,那就太好了。

此代码可正常使用“ value”作为选项元素的属性。

; (function ($, window, document, undefined) {
    $.fn.chainedTo = function (parentSelector = "",debugRules = false) {
        var $child = $(this);
        var thisChildId = "#" + $child[0].id;

        function setIdChild($id, childId) {
            if (typeof $id.data('updateChild') === 'undefined') {
                $id.attr('data-update-child', childId);
            } else {
                $id.attr('data-update-child', $id.attr('data-update-child') + ',' + childId);
            }
        };
        function setIdParent($id, parentId) {
            if (typeof $id.data('selectParent') === 'undefined') {
                $id.data('selectParent', new Array(parentId.split(",")));
            } else {
                $id.data('selectParent', $id.data('selectParent').concat(parentId.split(",")));
            }
        };
        function saveIdOldState($id) {
            if (typeof $id.data('old-state') === 'undefined') {
                $id.data('old-state', $id.html());
            }
        };

        function matchRule(str, rules, debugRules = false) {
            if (debugRules) console.log('      Parent values to match: ' + str);
            if (debugRules) console.log("      Rules to match with: " + rules);
            var ruleArr = rules;
            
            for (let i = 0; i < ruleArr.length; i++) {
                let thisRuleText = ruleArr[i].split("*").join(".*").split("+").join("\\+");
                let thisRule = new RegExp(thisRuleText);
                if (debugRules) console.log("      - Checking with RegExp: " + thisRule);

                if (thisRule.test(str)) {
                    if (debugRules) console.log("      # MATCHED on rule: " + thisRule);
                    return true;
                }
            }
            if (debugRules) console.log("      # NO MATCH found");
            return false;
        };
        function updateSelections($id) {
            //restore the original state for this select
            $id.html($id.data('old-state'));
            if ($id.attr('data-debug-rules') == "true") {
                var debugRules = true;
            }
            //get the current value of the parents we want to match, join with '+'
            if (typeof $id.data('selectParent') === 'undefined')
                return true;
            var parentVal = $($id.data('selectParent').join(",")).map(function () {
                return this.value;
            }).get().join("+");
            var newInnerHTML = [];
            //loop through each of the select options and remove where the parent value is not found
            if (debugRules) console.log("==> Evaluating select id: #" +$id.attr('id'));
            $id.children().each(function (k, value) {
                if (debugRules) console.log  (" -> Evaluating select option with text: " + value.innerText.trim());
                if (matchRule(parentVal, value.getAttribute('data-available-with').split(","), debugRules)) {
                    newInnerHTML += (value.outerHTML);
                }
            });
            $id.html(newInnerHTML);


        };


        function ClickTab(e) {
            if (typeof $(e.target).attr('data-update-child') === 'undefined')
                return true;

            //get and split the children. For each of those, update the valid selections.
            for (let i = 0; i < $(e.target).attr('data-update-child').split(",").length; i++) {
                updateSelections($($(e.target).attr('data-update-child').split(",")[i]));
            }
            return false;
        };

        //Save the original state of the select in a datafield
        saveIdOldState($child);
//        console.log($(parentSelector));

        //enabling rules debug if requested
        if (debugRules) $child.attr('data-debug-rules', 'true');

        //configure a change trigger on the parent selector
        $(parentSelector).filter(function () {
            return $(this).data('updateChild') === undefined;
        }).change(ClickTab);

        //add a data record to the parent that links it to the child
        $(parentSelector).each(function (k, v) {
            setIdChild($(v), thisChildId);
//            console.log("parentSelector each value: ", $(v));
        });

        //add a data record to the child that links it to the parent.
        setIdParent($child, parentSelector);

        //update the selections right now.
        updateSelections($child);


        // return jQuery object
        return this;
    };


})(jQuery, window, document);




    $("#desktoptype").chainedTo("#datacenter");
    // $("#os").chainedTo("#datacenter,#desktoptype");
    $("#os").chainedTo("#desktoptype");
    $("#bu").chainedTo("#datacenter,#desktoptype,#os");
    $("#as").chainedTo("#bu");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset id="chained-set">
        <select id="datacenter" class="form-control">
            <option value="1">ONE</option>
            <option value="2">ONE+</option>
        </select>

        <select id="desktoptype" class="form-control">
            <option value="1" data-available-with="1">ONE RUN</option>
            <option value="2" data-available-with="2">ONE+ RUN</option>
        </select>
        <select id="os" class="form-control">
            <option value="1" data-available-with="1,2">1 Color</option>
            <option value="3" data-available-with="1,2">2 Colors</option>
        </select>
        <select id="bu" class="form-control">
			<option value="" data-available-with="1,2">No</option>
            <option value="4" data-available-with="1,2">Yes</option>
        </select>
		<select id="as" class="form-control">
			<option value="4" data-available-with="4">Yes</option>
        </select>
    </fieldset>

如果我更新HTML以使“ test”成为选项元素的属性,我希望它能够正常工作。

 <fieldset id="chained-set">
        <select id="datacenter" class="form-control">
            <option test="1">ONE</option>
            <option test="2">ONE+</option>
        </select>
        <select id="desktoptype" class="form-control">
            <option test="1" data-available-with="1">ONE RUN</option>
            <option test="2" data-available-with="2">ONE+ RUN</option>
        </select>
        <select id="os" class="form-control">
            <option test="1" data-available-with="1,2">1 Color</option>
            <option test="3" data-available-with="1,2">2 Colors</option>
        </select>
        <select id="bu" class="form-control">
			<option test="" data-available-with="1,2">No</option>
            <option test="4" data-available-with="1,2">Yes</option>
        </select>
		<select id="as" class="form-control">
			<option test="4" data-available-with="4">Yes</option>
        </select>
    </fieldset>
    
        

2 个答案:

答案 0 :(得分:0)

test不是标准的HTML属性,因此不适用于您的用例。相反,HTML5引入了我们所谓的自定义数据属性。这些允许我们将任意字符串存储为HTML中的属性。自定义数据属性以data-开头,以避免造成混淆,并将该属性区分为页面唯一。

此代码看起来像使用jQuery。 jQuery具有用于与元素数据进行交互的接口,该接口可能对您的用例有用。我建议阅读this link上的API文档。

答案 1 :(得分:0)

如果您只是想从自定义的html元素中检索数据,请将Apple developer portal选项与HTML5 data-* attribute结合使用。

capybara-webkit
$(document).ready(function() {
  $('[data-blah]').each(function(i,e){
    var $this = $(e);
    var data = $this.data('blah');
    $this.text(data);
  });
});