weixin_33670786 2017-02-04 07:53 采纳率: 0%
浏览 78

如何在js中编码数字?

I want to encode a number in which url passed in tag in js. I am trying to encodeURIComponent() but this is not working.

This tag included in js code:

<a href="index.php?act=viw_product&id=encodeURIComponent('+val['id']+')" > </a>

I need to encode a id in base64 format?

  • 写回答

1条回答 默认 最新

  • weixin_33726313 2017-02-04 08:21
    关注

    It isn't working because, with a few exceptions, JavaScript won't arbitrarily run inside parameters on HTML elements. HTML parameters are just ordinary strings.

    I think there are more fundamental issues with your code, but at the very least, to encode the value and add it to a string you need to change how you're concatenating the values together.

    var url = 'index.php?act=viw_product&id=' + encodeURIComponent(val['id']);
    

    This takes the val['id'] and encodes it, then appends it to the end of the path string and stores it in the url variable.

    Now url will contain the entire the path with the encoded number at the end. However, you'll need to actually tell your script to find that <a> tag and set the href parameter equal to that value for it to work.

    Here's a basic example in raw javascript:

    // find out link element
    var el = document.querySelector('a');
    
    // encode our URL with a wacky ID
    var id = '1#B!70_4';
    var url = 'index.php?act=viw_product&id=' + encodeURIComponent(id);
    
    // set the URL on our href attribute
    el.setAttribute('href', url);
    <a href="#">click me</a>

    If you run the above example and hover over the link, you can see the generated URL that's been applied to the links href attribute.

    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)