簡體   English   中英

在html標記內使用'javascript:'

[英]Using 'javascript:' inside html tag

我正在使用node.js開發Web服務器。 但是我現在遇到了一個問題。 下面的代碼是我的HTML代碼。

<%
  var tagID = 'something';
%>
<a href="..." id="javascript:tagID">...</a>

我知道如果我在HTML標記內使用'javascript:'。 然后可以執行javascript代碼。 但是當我在瀏覽器中檢查它時,它不起作用。

還是我應該使用DOM來做到這一點?

您可以在href中使用javascript: :。 像這樣

<a href="javascript:alert('hello')">Hi</a>

您可以使用https://www.npmjs.com/package/ejs

// server.js
// load the things we need
var express = require('express');
var app = express();

// set the view engine to ejs
app.set('view engine', 'ejs');

// use res.render to load up an ejs view file

// index page 
app.get('/', function(req, res) {
    res.render('pages/index');
});

// about page 
app.get('/about', function(req, res) {
    res.render('pages/about');
});

app.listen(8080);
console.log('8080 is the magic port');

你可以像這樣嵌入javascript

<ul>
    <% drinks.forEach(function(drink) { %>
        <li><%= drink.name %> - <%= drink.drunkness %></li>
    <% }); %>
</ul>
<!DOCTYPE html>
<html lang="en">
<head>
    <% include ../partials/head %>
</head>
<body class="container">

<header>
    <% include ../partials/header %>
</header>

<main>
    <div class="jumbotron">
        <h1>This is great</h1>
        <p>Welcome to templating using EJS</p>
    </div>
</main>

<footer>
    <% include ../partials/footer %>
</footer>

</body>
</html>

有3種方法可以完成您要問的事情:

  1. 使用諸如angular的單頁應用程序,做出反應...

  2. 使用您自己的自定義設計模式將替換您要替換的任何內容

 var global = this; global.id1 = 10; global.id2 = 30; document.querySelectorAll("*").forEach(function(dom) { [...dom.attributes].forEach(function(attr) { if (attr.value.startsWith("javascript:")) { dom.setAttribute(attr.name, global[attr.value.replace("javascript:", "")]); } }); }); 
 <div id="javascript:id1">Div 1</div> <div id="javascript:id2">Div 2</div> 

  1. 手動執行更新

 document.getElementById("1").id = "10"; document.getElementById("2").id = "20"; 
 <div id="1">Div 1</div> <div id="2">Div 2</div> 

如果您要創建一個大型應用程序,那么我建議您使用一個頁面應用程序(盡管如果您熟悉它,可能需要一些時間來了解其工作原理)。

如果您喜歡冒險或不想打擾學習或使用SPA,可以創建自己的框架/設計模式。

如果您顯示的示例不常見(並且您不希望將來出現這種情況),最簡單的解決方案是手動更新dom。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM