前端HTML拼接js时,用onclick等方法传递对象解决办法

2022-01-07  本文已影响0人  泽赫

关键代码:

JSON.stringify(data).replace(/"/g, "\'")
//关键代码 :将字符串中的单引号改成双引号,只有这样JSON.parse才能用
const regex= jsonData.replace(/'/g, '"')
const parseData = JSON.parse(regex)
解决根本问题:传参报错,或者传参是’[object,object]‘不能解析问题以及Unexpected token ' in JSON at position 1等问题

const data ={
        address: '仙林大道163号',
        areaName: '秦淮区',
        cityName: '南京市',
        id: 2,
        latitude: 32.11956,
        locationName: '南京大学仙林校区2',
        longitude: 118.958406,
        provinceName: '江苏省'
      }
const jsonData = JSON.stringify(data).replace(/"/g, "\\'")
const startStyle =
    'padding:5px;background-color:rgb(236, 245, 255);font-size:12px;border:1px solid #409eff;color:#409eff;cursor:pointer'
const endStyle =
    'padding:5px;background-color:rgb(254, 240, 240);font-size:12px;border:1px solid #f56c6c;color:#f56c6c;cursor:pointer;margin-left:10px'

return `<div style="padding:0 5px">
    <button style="${startStyle}" onClick="setStart('${jsonData}')">
      设为起点
    </button>
    <button style="${endStyle}" onClick="setEnd('${locationName}','${longitude}','${latitude}')">
      设为终点
    </button>
  </div>

const setStart = (jsonData, lng, lat) => {
  //关键代码 :将字符串中的单引号改成双引号,只有这样JSON.parse才能用
  const  regex= jsonData.replace(/'/g, '"')
  const parseData = JSON.parse(regex)
  }
上一篇 下一篇

猜你喜欢

热点阅读