简体   繁体   English

在函数中传递参数

[英]pass parameter in function

I want to pass string and integer parameters through a javascript function, but the integer passes as string. 我想通过javascript函数传递字符串和整数参数,但是整数作为字符串传递。

The variable attachfile is a string. 变量attachfile是一个字符串。

var upload_number = 1;

input.setAttribute("onClick", "removeBtn(attachfile+ upload_number)");

you can use jquery to convert that to a number or you can use parseInt(your_variable,10) 您可以使用jquery将其转换为数字,也可以使用parseInt(your_variable,10)

10 here is a radix 10是一个基数

EDIT 编辑

I meant jquery to validate whether its a number 我的意思是jquery验证其是否为数字

Javascript has a parseInt() function. Javascript具有parseInt()函数。 The parseInt() function parses a string and returns an integer. parseInt()函数解析一个字符串并返回一个整数。

The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number. 基数参数用于指定要使用的数字系统,例如,基数16(十六进制)表示应将字符串中的数字从十六进制数字解析为十进制数字。

If the radix parameter is omitted, JavaScript assumes the following: 如果省略了radix参数,则JavaScript假定以下内容:

  • If the string begins with "0x", the radix is 16 (hexadecimal) If the 如果字符串以“ 0x”开头,则基数为16(十六进制)。
  • string begins with "0", the radix is 8 (octal). 字符串以“ 0”开头,基数为8(八进制)。 This feature is 此功能是
  • deprecated If the string begins with any other value, the radix is 10 (decimal) 如果字符串以任何其他值开头,则基数为10(十进制)

Syntax: 句法:

parseInt(string, radix)

(stolen from here ) (从这里被盗)

It would help if you showed the declaration for your removeBtn() function, but the problem seems to be that you are not passing two parameters to the function, you are passing one parameter that takes the value of attachfile concatenated with upload_number - and when you concatenate a string with a number the result is a string. 如果显示了removeBtn()函数的声明会有所帮助,但是问题似乎是您没有向该函数传递两个参数,而是传递了一个参数,该参数采用与upload_number串联的attachfile的值-当您将字符串与数字连接起来,结果是一个字符串。

You need to pass the parameters separately, ie, instead of: 您需要分别传递参数,即,而不是:

removeBtn(attachfile+ upload_number)

Use: 采用:

removeBtn(attachfile, upload_number)

Then the declaration of removeBtn() should be: 然后, removeBtn()的声明应为:

function removeBtn(theFile, theNumber) { // name the parameters however you like

(By the way, the way you are setting the onclick attribute to a string that contains a function call may also be causing you some problems because (amongst other issues) that function and the parameters would need to be globals. But that's - possibly - outside the scope of this question, at least unless you update it to show more of your code.) (顺便说一句,将onclick属性设置为包含函数调用的字符串的方式也可能会引起一些问题,因为(除其他问题外)该函数和参数需要是全局变量。但是-可能-超出此问题的范围,至少除非您对其进行更新以显示更多代码。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM