HTML自定义属性始终在Jquery中返回undefined

时间:2016-03-03 04:56:59

标签: javascript jquery html

我有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中调试时)。什么遗失?

艾伦

3 个答案:

答案 0 :(得分:2)

$this给出了不同的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) {

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

答案 1 :(得分:1)

$(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-*属性创建自己的自定义属性。

答案 2 :(得分:0)

正如上面其他人所说的那样,这个val内部自动完成与外面的不同。

要使代码工作,请按以下方式替换代码:

$(":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) {

                        }

                });
            }
        });
    });

超出此值: 输入#搜索

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)