javascript 动态添加锚标签到页面,作为点击时弹出的窗口

wwwo4jvm  于 2023-01-11  发布在  Java
关注(0)|答案(3)|浏览(158)
    • bounty将在5天后过期**。回答此问题可获得+50声望奖励。Swetha希望引起更多人关注此问题。

尝试在提交按钮后的下方div中添加锚标记。

<div align="center" id="idSection">
        <input type="text" id="first"  placeholder="Enter id here..." maxlength="11" />
        <input type="button" id="submit"  value="Submit" />
</div>
$("div#idSection").append('<a href=http://localhost/request+{argument passed dynamically after clicking on submit button}+' onclick = "window.open('href=http://localhost/request+{argument passed dynamically after clicking on submit button}'">REPORT</a>);
nszi6y05

nszi6y051#

试试看这是否适合你的要求。在你的机器上运行它,因为锚标记中的"target"属性在下面的代码段中不起作用。

$("#submit").click(function () {
  var id = $("#first").val();
  console.log(id);
  
  var requestURL = "http://localhost/request?id=" + id;
  console.log(requestURL);
  
  var anchorTag = '<a href="' + requestURL + '" target="_blank">REPORT</a>';
  console.log(anchorTag);

  $("div#idSection").append(anchorTag);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div align="center" id="idSection">
  <input type="text" id="first" placeholder="Enter id here..." maxlength="11" />
  <input type="button" id="submit" value="Submit" />
</div>
tnkciper

tnkciper2#

你的问题有点模糊,如果你的代码中有“{argument passed dynamically after click on submit button}",我会假设你指的是id为“first”的文本输入内容,并且当点击附加的<a>标签时,你指定的URL需要附加'?id=the-value-of-the-id-text-widget'。
<a>标记被单击时,应该不需要使用JavaScript open函数来转到新的URL;将URL指定为 href 参数就足够了:

$( "#submit" ).click(function( event ) {
  let id = $('#first').val();
  let url = '<a id="a" href="http://localhost/request?id=' + id + '">REPORT</a>';
  // Get rid of any previous <a> tag:
  if ($('#a')) {
      $('#a').remove();
  }
  $('#idSection').append($(url));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div align="center" id="idSection">
        <input type="text" id="first"  placeholder="Enter id here..." maxlength="11" />
        <input type="button" id="submit"  value="Submit" />
</div>
y53ybaqx

y53ybaqx3#

您也可以在纯JavaScript中实现此要求。
现场演示**:**

const sbmtBtn = document.getElementById('submit');

sbmtBtn.addEventListener("click", addLink);

function addLink() {
  const inputVal = document.getElementById('first').value.trim();
  const linkElement = document.getElementById('link');
  
  if(linkElement) linkElement.remove();
  
  if (inputVal) {
    const anchorElement = `<a id="link" href="http://localhost/request?id=${inputVal}" target="_blank"> LINK </a>`;
    document.getElementById("submit").insertAdjacentHTML("afterend", anchorElement);
  } else {
    alert('ID field is required');
  }
}
<div align="center" id="idSection">
  <input type="text" id="first"  placeholder="Enter id here..." maxlength="11" />
  <input type="button" id="submit" value="Submit" />
</div>

相关问题