Javascript 未捕获的 ReferenceError:赋值中的左侧无效

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1945302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:00:31  来源:igfitidea点击:

Uncaught ReferenceError: Invalid left-hand side in assignment

javascriptjqueryclick

提问by sebastian rus

<script>
function urlencode(str) {
   return escape(str).replace('+', '%2B').replace('%20', '+').replace('*', '%2A').replace('/', '%2F').replace('@', '%40');
}
$('input#q').keyup(function(e) {
 if(e.keyCode == 13) {
  if($('input#q').val().length > 2) 
  { 
   $('input#q').val() = urlencode($('input#q').val());
   document.search_form.submit();
  }
 }
});
$('input#search').click(function() {
 if($('input#q').val().length > 2) 
 { 
  $('input#q').val() = urlencode($('input#q').val());
  document.search_form.submit();
 } 
});
</script>

when i click the search button i get the following error : "Uncaught ReferenceError: Invalid left-hand side in assignment" But the code is actually the same as when i press "enter". Can someone explain?

当我单击搜索按钮时,我收到以下错误:“未捕获的 ReferenceError:分配中的左侧无效”但代码实际上与我按“输入”时相同。有人可以解释一下吗?

回答by Alex Gyoshev

You can't assign a new value to the result of a function

您不能为函数的结果分配新值

$('input#q').val() = urlencode($('input#q').val());

Use this instead:

改用这个:

$('input#q').val(urlencode($('input#q').val()))

It wouldn't work with the keypress either - maybe the page is simply submitted after the same js error occurs.

它也不适用于按键 - 也许页面只是在发生相同的 js 错误后提交。

回答by coder

Why are you assinging a result of a function like this:

为什么要对这样的函数进行结果赋值:

$("input#q").val = urlencode($('input#q').val())

Use this instead

改用这个

$("input").val(urlencode($('input#q').val())