用javascript替换src元素

k5ifujac  于 2023-01-16  发布在  Java
关注(0)|答案(1)|浏览(187)

我正在为一个项目创建一个简单的内容构建器,当有人点击一张图片时,会打开一个对话框,要求他们输入url来替换src,输入一个新的alt,输入一个新的title它应该替换下面img标签中的每一个元素
之前:

<div class="three">
    <!-- 1 Image -->
    <img id="imageid" src="https://cdn.shopify.com/s/files/1/0645/1401/files/Wellness_700x.png" class="lazyload--fade-in lazyautosizes lazyloaded" alt="" title="" data-iml="333">
</div>`

结果:

<div class="three">https://storage.googleapis.com/support-kms-prod/RrjdySjRxcYJL3NpcXaobwTxuk7zctDbL8rX</div>

法典

$('.main').on('click', '.element',function(e){
  console.log('Delete Element? ', isDelete(e,this));
  currentSelected = e.target;
  if(!isDelete(e,this)) {
    if(e.target.tagName == "IMG") {
      let imgUrl = prompt('Enter URL Here');
      let imgAlt = prompt('Enter Alt Text Here');
      let imgTitle = prompt('Enter Title Here');
      e.target.parentNode.innerHTML = imgUrl.replace('src=');e.target.parentNode.innerHTML = imgAlt.replace('alt=');
      e.target.parentNode.innerHTML = imgTitle.replace('title=');
    } else if (['h2', 'h3', 'h4', 'h5', 'h6', 'a','p', 'li', 'iframe'].includes(e.target.localName)) {
      if(e.target.localName == 'a') {
        e.target.innerText = prompt('Enter Call To Action Text') + " →";
      } else {
        e.target.innerText = prompt('Enter Heading Text Here');
      }
    }
  } else {
    e.target.remove();
  }
  const code = $('.main__layout-content')[0].outerHTML.replace(/"/g, `'`).split('\n').join('');
  setCookie("code", code, 10);
fzsnzjdm

fzsnzjdm1#

如果你必须替换html元素上的任何属性值,只要用简单的方法就可以了:

// once you have checked that the event target is the img elmt you want...
const img_elmt = e.target;
e.target.src = some_url;

相关问题