[英]Why doesn't this js array function work?
I'm using the jQuery library, and attempting to push items to an array: 我正在使用jQuery库,并尝试将项目推入数组:
< onclick ="setFacet('myarray','val');">AOC
var myarray = [];
function setFacet(arr, bb) {
for (var i=0; i< arr.length; i++)
if (arr[i] == bb)
return true;
arr.push(bb);
return false;
}
I get this in chrome: 我得到这个镀铬:
Object myarray has no method 'push' 对象myarray没有方法“推”
Oh, I think I found the issue. 哦,我想我找到了问题。 In your
onclick
, you're calling the function with two strings . 在
onclick
,您将使用两个字符串来调用该函数。 The first argument should be an array rather than 'myarray'
. 第一个参数应该是一个数组,而不是
'myarray'
。
If you just get rid of the quotes (and if myArray
is in the global scope) it should work. 如果您只删除引号(并且
myArray
在全局范围内),则应该可以使用。 That is, have it look like this: 也就是说,它看起来像这样:
onclick="setFacet(myArray, 'val')"
Change: 更改:
onclick="setFacet('myarray','val')"
To: 至:
onclick="setFacet(myarray)"
then change the function setFacet
to the following: 然后将函数
setFacet
更改为以下内容:
function setFacet(arr, bb) {
for (var i=0; i< arr.length; i++)
if (arr[i] == bb) return true;
arr.push(this.innerHTML); /* "this" in the context of the "click" */
/* is the element clicked */
return false;
}
the element with the onclick listener should be 具有onclick侦听器的元素应为
<...onclick ="setFacet(myarray,'val');">
myarray should not be quoted, otherwise it will be treated as a string. myarray不应用引号引起来,否则将被视为字符串。
You could separate your javascript from your markup altogether and just store the value as an attribute of the clicked element (or any other element) 您可以将JavaScript与标记完全分开,然后将值存储为clicked元素(或任何其他元素)的属性
<input type="button" value="someValue">
<script>
$(function(){
var myArray = [];
$('#myEle').click(function(){
myArray.push($(this).val())
})
})
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.