簡體   English   中英

HTML自定義屬性始終在Jquery中返回未定義

[英]HTML custom attribute always return undefined in Jquery

我有如下的HTML元素

<input type="text" id="Search" select-box-search="true" select-box-search-url="testURL" /> 

我有如下的jQuery。

 $(":input[select-box-search]").each(function () {
        $(this).autocomplete({
            source: function (request) {
                var url = $(this).attr("select-box-search-url");
                $.ajax({
                    async: false,
                    cache: false,
                    type: "POST",
                    url: url,
                    data: { "term": request.term},
                    success: function (data) {

                        }
                    }
                });
            }
        });
    });

“ URL”始終是未定義的。 但是,“ this”是指正確的元素(在Chrome中調試時)。 缺少什么?

艾倫

$this context inside the source: function (request)提供了不同的context inside the source: function (request) 。因此,在進入函數之前,您需要緩存元素

 $(":input[select-box-search]").each(function () {
    var $element = $(this);
    $element.autocomplete({
        source: function (request) {
            var url = $element.attr("select-box-search-url");
            $.ajax({
                async: false,
                cache: false,
                type: "POST",
                url: url,
                data: { "term": request.term},
                success: function (data) {

                    }
                }
            });
        }
    });
});

$(this)將在自動完成功能內提供不同的上下文。 嘗試這個 :-

$(":input[select-box-search]").each(function () {
        var $this = $(this); //store $(this) reference inside a variable
        $(this).autocomplete({
            source: function (request) {
                var url = $this.attr("select-box-search-url"); //change here
                $.ajax({
                    async: false,
                    cache: false,
                    type: "POST",
                    url: url,
                    data: { "term": request.term},
                    success: function (data) {

                        }
                    }
                });
            }
        });
 });

注意 :-使用HTML5 data-*屬性而不是使用自己的自定義屬性。

如前兩個所述,內部自動完成的值與此外部不同。

為了使您的代碼正常工作,請按以下步驟替換代碼:

$(":input[select-box-search]").each(function () {
        $(this).autocomplete({
            source: function (request) {

var url = $(this.element).attr('select-box-search');

                $.ajax({
                    async: false,
                    cache: false,
                    type: "POST",
                    url: url,
                    data: { "term": request.term},
                    success: function (data) {

                        }

                });
            }
        });
    });

超出此值:input#Search

accept: ""
accessKey: ""
align: ""
alt: ""
attributes: NamedNodeMap
autocapitalize: "sentences"
autocomplete: ""
autofocus: false
baseURI: "file:///Users/avagrawal/Desktop/sent/hammer/index.html"
checked: false
childElementCount: 0
childNodes: NodeList[0]
children: HTMLCollection[0]
classList: DOMTokenList[0]
className: ""
clientHeight: 15
clientLeft: 2
clientTop: 2
clientWidth: 127
contentEditable: "inherit"
dataset: DOMStringMap
defaultChecked: false
defaultValue: ""
dir: ""
dirName: ""
disabled: false
draggable: false
files: null
firstChild: null
firstElementChild: null
form: null
formAction: "file:///Users/avagrawal/Desktop/sent/hammer/index.html"
formEnctype: ""
formMethod: ""
formNoValidate: false
formTarget: ""
height: 0
hidden: false
id: "Search"
incremental: false
indeterminate: false
innerHTML: ""
innerText: ""
isContentEditable: false
labels: NodeList[0]
lang: ""
lastChild: null
lastElementChild: null
list: null
localName: "input"
max: ""
maxLength: 524288
min: ""
minLength: 0
multiple: false
name: ""
namespaceURI: "http://www.w3.org/1999/xhtml"
nextElementSibling: div#number.abc
nextSibling: text
nodeName: "INPUT"
nodeType: 1
nodeValue: null
offsetHeight: 19
offsetLeft: 8
offsetParent: body
offsetTop: 8
offsetWidth: 131
onabort: null
onautocomplete: null
onautocompleteerror: null
onbeforecopy: null
onbeforecut: null
onbeforepaste: null
onblur: null
oncancel: null
oncanplay: null
oncanplaythrough: null
onchange: null
onclick: null
onclose: null
oncontextmenu: null
oncopy: null
oncuechange: null
oncut: null
ondblclick: null
ondrag: null
ondragend: null
ondragenter: null
ondragleave: null
ondragover: null
ondragstart: null
ondrop: null
ondurationchange: null
onemptied: null
onended: null
onerror: null
onfocus: null
oninput: null
oninvalid: null
onkeydown: null
onkeypress: null
onkeyup: null
onload: null
onloadeddata: null
onloadedmetadata: null
onloadstart: null
onmousedown: null
onmouseenter: null
onmouseleave: null
onmousemove: null
onmouseout: null
onmouseover: null
onmouseup: null
onmousewheel: null
onpaste: null
onpause: null
onplay: null
onplaying: null
onprogress: null
onratechange: null
onreset: null
onresize: null
onscroll: null
onsearch: null
onseeked: null
onseeking: null
onselect: null
onselectstart: null
onshow: null
onstalled: null
onsubmit: null
onsuspend: null
ontimeupdate: null
ontoggle: null
onvolumechange: null
onwaiting: null
onwebkitfullscreenchange: null
onwebkitfullscreenerror: null
onwheel: null
outerHTML: "<input type="text" id="Search" select-box-search="true" select-box-search-url="testURL">"
outerText: ""
ownerDocument: document
parentElement: body
parentNode: body
pattern: ""
placeholder: ""
prefix: null
previousElementSibling: script
previousSibling: text
readOnly: false
required: false
scrollHeight: 15
scrollLeft: 0
scrollTop: 0
scrollWidth: 127
selectionDirection: "none"
selectionEnd: 0
selectionStart: 0
shadowRoot: null
size: 20
spellcheck: true
src: ""
step: ""
style: CSSStyleDeclaration
tabIndex: 0
tagName: "INPUT"
textContent: ""
title: ""
translate: true
type: "text"
useMap: ""
validationMessage: ""
validity: ValidityState
value: ""
valueAsDate: null
valueAsNumber: NaN
webkitEntries: Array[0]
webkitdirectory: false
webkitdropzone: ""
width: 0
willValidate: true
__proto__: HTMLInputElement

在此值內

    $.(…).(anonymous
    function) {
    element: n.fn.init[1],
    uuid: 0,
    eventNamespace: ".autocomplete0",
    options: Object,
    bindings: n.fn.init[3]…
}
_super: () _superApply: (args) bindings: n.fn.init[3] 0: input# Search.ui - autocomplete - input.ui - autocomplete - loading1: ul# ui - id - 1. ui - autocomplete.ui - front.ui - menu.ui - widget.ui - widget - content.ui - corner - all2: Windowcontext: undefinedlength: 3 prevObject: n.fn.init[2] __proto__: n[0] cancelSearch: falsedocument: n.fn.init[1] 0: documentcontext: documentlength: 1 __proto__: n[0] element: n.fn.init[1] 0: input# Search.ui - autocomplete - input.ui - autocomplete - loadingaccept: ""
accessKey: ""
align: ""
alt: ""
attributes: NamedNodeMapautocapitalize: "sentences"
autocomplete: "off"
autofocus: falsebaseURI: "file:///Users/avagrawal/Desktop/sent/hammer/index.html"
checked: falsechildElementCount: 0 childNodes: NodeList[0] children: HTMLCollection[0] classList: DOMTokenList[2] className: "ui-autocomplete-input ui-autocomplete-loading"
clientHeight: 15 clientLeft: 2 clientTop: 2 clientWidth: 127 contentEditable: "inherit"
dataset: DOMStringMapdefaultChecked: falsedefaultValue: ""
dir: ""
dirName: ""
disabled: falsedraggable: falsefiles: nullfirstChild: nullfirstElementChild: nullform: nullformAction: "file:///Users/avagrawal/Desktop/sent/hammer/index.html"
formEnctype: ""
formMethod: ""
formNoValidate: falseformTarget: ""
height: 0 hidden: falseid: "Search"
incremental: falseindeterminate: falseinnerHTML: ""
innerText: ""
isContentEditable: falsejQuery2210183872326975688342: ObjectjQuery2210183872326975688341: Objectlabels: NodeList[0] lang: ""
lastChild: nulllastElementChild: nulllist: nulllocalName: "input"
max: ""
maxLength: 524288 min: ""
minLength: 0 multiple: falsename: ""
namespaceURI: "http://www.w3.org/1999/xhtml"
nextElementSibling: span.ui - helper - hidden - accessiblenextSibling: span.ui - helper - hidden - accessiblenodeName: "INPUT"
nodeType: 1 nodeValue: nulloffsetHeight: 19 offsetLeft: 8 offsetParent: bodyoffsetTop: 8 offsetWidth: 131 onabort: nullonautocomplete: nullonautocompleteerror: nullonbeforecopy: nullonbeforecut: nullonbeforepaste: nullonblur: nulloncancel: nulloncanplay: nulloncanplaythrough: nullonchange: nullonclick: nullonclose: nulloncontextmenu: nulloncopy: nulloncuechange: nulloncut: nullondblclick: nullondrag: nullondragend: nullondragenter: nullondragleave: nullondragover: nullondragstart: nullondrop: nullondurationchange: nullonemptied: nullonended: nullonerror: nullonfocus: nulloninput: nulloninvalid: nullonkeydown: nullonkeypress: nullonkeyup: nullonload: nullonloadeddata: nullonloadedmetadata: nullonloadstart: nullonmousedown: nullonmouseenter: nullonmouseleave: nullonmousemove: nullonmouseout: nullonmouseover: nullonmouseup: nullonmousewheel: nullonpaste: nullonpause: nullonplay: nullonplaying: nullonprogress: nullonratechange: nullonreset: nullonresize: nullonscroll: nullonsearch: nullonseeked: nullonseeking: nullonselect: nullonselectstart: nullonshow: nullonstalled: nullonsubmit: nullonsuspend: nullontimeupdate: nullontoggle: nullonvolumechange: nullonwaiting: nullonwebkitfullscreenchange: nullonwebkitfullscreenerror: nullonwheel: nullouterHTML: "<input type="
text " id="
Search " select-box-search="
true " select-box-search-url="
testURL " class="
ui - autocomplete - input ui - autocomplete - loading " autocomplete="
off ">"
outerText: ""
ownerDocument: documentparentElement: bodyparentNode: bodypattern: ""
placeholder: ""
prefix: nullpreviousElementSibling: scriptpreviousSibling: textreadOnly: falserequired: falsescrollHeight: 15 scrollLeft: 0 scrollTop: 0 scrollWidth: 127 selectionDirection: "none"
selectionEnd: 1 selectionStart: 1 shadowRoot: nullsize: 20 spellcheck: truesrc: ""
step: ""
style: CSSStyleDeclarationtabIndex: 0 tagName: "INPUT"
textContent: ""
title: ""
translate: truetype: "text"
useMap: ""
validationMessage: ""
validity: ValidityStatevalue: "a"
valueAsDate: nullvalueAsNumber: NaNwebkitEntries: Array[0] webkitdirectory: falsewebkitdropzone: ""
width: 0 willValidate: true__proto__: HTMLInputElementcontext: input# Search.ui - autocomplete - input.ui - autocomplete - loadingaccept: ""
accessKey: ""
align: ""
alt: ""
attributes: NamedNodeMapautocapitalize: "sentences"
autocomplete: "off"
autofocus: falsebaseURI: "file:///Users/avagrawal/Desktop/sent/hammer/index.html"
checked: falsechildElementCount: 0 childNodes: NodeList[0] children: HTMLCollection[0] classList: DOMTokenList[2] className: "ui-autocomplete-input ui-autocomplete-loading"
clientHeight: 15 clientLeft: 2 clientTop: 2 clientWidth: 127 contentEditable: "inherit"
dataset: DOMStringMapdefaultChecked: falsedefaultValue: ""
dir: ""
dirName: ""
disabled: falsedraggable: falsefiles: nullfirstChild: nullfirstElementChild: nullform: nullformAction: "file:///Users/avagrawal/Desktop/sent/hammer/index.html"
formEnctype: ""
formMethod: ""
formNoValidate: falseformTarget: ""
height: 0 hidden: falseid: "Search"
incremental: falseindeterminate: falseinnerHTML: ""
innerText: ""
isContentEditable: falsejQuery2210183872326975688342: ObjectjQuery2210183872326975688341: Objectlabels: NodeList[0] lang: ""
lastChild: nulllastElementChild: nulllist: nulllocalName: "input"
max: ""
maxLength: 524288 min: ""
minLength: 0 multiple: falsename: ""
namespaceURI: "http://www.w3.org/1999/xhtml"
nextElementSibling: span.ui - helper - hidden - accessiblenextSibling: span.ui - helper - hidden - accessiblenodeName: "INPUT"
nodeType: 1 nodeValue: nulloffsetHeight: 19 offsetLeft: 8 offsetParent: bodyoffsetTop: 8 offsetWidth: 131 onabort: nullonautocomplete: nullonautocompleteerror: nullonbeforecopy: nullonbeforecut: nullonbeforepaste: nullonblur: nulloncancel: nulloncanplay: nulloncanplaythrough: nullonchange: nullonclick: nullonclose: nulloncontextmenu: nulloncopy: nulloncuechange: nulloncut: nullondblclick: nullondrag: nullondragend: nullondragenter: nullondragleave: nullondragover: nullondragstart: nullondrop: nullondurationchange: nullonemptied: nullonended: nullonerror: nullonfocus: nulloninput: nulloninvalid: nullonkeydown: nullonkeypress: nullonkeyup: nullonload: nullonloadeddata: nullonloadedmetadata: nullonloadstart: nullonmousedown: nullonmouseenter: nullonmouseleave: nullonmousemove: nullonmouseout: nullonmouseover: nullonmouseup: nullonmousewheel: nullonpaste: nullonpause: nullonplay: nullonplaying: nullonprogress: nullonratechange: nullonreset: nullonresize: nullonscroll: nullonsearch: nullonseeked: nullonseeking: nullonselect: nullonselectstart: nullonshow: nullonstalled: nullonsubmit: nullonsuspend: nullontimeupdate: nullontoggle: nullonvolumechange: nullonwaiting: nullonwebkitfullscreenchange: nullonwebkitfullscreenerror: nullonwheel: nullouterHTML: "<input type="
text " id="
Search " select-box-search="
true " select-box-search-url="
testURL " class="
ui - autocomplete - input ui - autocomplete - loading " autocomplete="
off ">"
outerText: ""
ownerDocument: documentparentElement: bodyparentNode: bodypattern: ""
placeholder: ""
prefix: nullpreviousElementSibling: scriptpreviousSibling: textreadOnly: falserequired: falsescrollHeight: 15 scrollLeft: 0 scrollTop: 0 scrollWidth: 127 selectionDirection: "none"
selectionEnd: 1 selectionStart: 1 shadowRoot: nullsize: 20 spellcheck: truesrc: ""
step: ""
style: CSSStyleDeclarationtabIndex: 0 tagName: "INPUT"
textContent: ""
title: ""
translate: truetype: "text"
useMap: ""
validationMessage: ""
validity: ValidityStatevalue: "a"
valueAsDate: nullvalueAsNumber: NaNwebkitEntries: Array[0] webkitdirectory: falsewebkitdropzone: ""
width: 0 willValidate: true__proto__: HTMLInputElementlength: 1 __proto__: n[0] eventNamespace: ".autocomplete0"
focusable: n.fn.init[0] hoverable: n.fn.init[0] isMultiLine: falseisNewMenu: trueliveRegion: n.fn.init[1] menu: $.(anonymous
    function).(anonymous
    function) options: Objectpending: 1 previous: ""
searching: 3 selectedItem: nullsource: (request) term: "a"
uuid: 0 valueMethod: (a) window: n.fn.init[1] __proto__: $.(anonymous
    function).(anonymous
    function)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM