2 回答

TA貢獻2036條經(jīng)驗 獲得超8個贊
我不明白你為什么要把鏈接包裝成表格。您可以將其從表單中刪除,然后簡單地執(zhí)行以下操作:
function more(e) {
e.preventDefault();
document.getElementById("atext").outerHTML = 'It touches many issues in our lives and packs a hell of a plot twist';
}
<a onClick="more(event)">Read More</a>
<p id="atext"></p>
此外,您可以href從鏈接中刪除,因為您正在阻止默認操作。

TA貢獻1817條經(jīng)驗 獲得超14個贊
您真的應該改掉編碼方式的習慣,它不僅已經(jīng)過時 20 多年,而且還很臟。抱歉吐槽了!
我的建議是創(chuàng)建一個可以重用的函數(shù),而不是只關(guān)注一個 ID,就好像需要在同一頁面上再次使用一樣,您不能多次使用相同的 ID,因此您將復制該函數(shù)。
另外(對我來說?。┦褂?onclick 變量是一個很大的禁忌,不需要......即使在 JS 中也讓它面向?qū)ο蟛⒍ㄎ稽c擊。
還有一件事; 您如何動態(tài)添加顯示的文本不會對您有任何幫助。在 SEO / SE 索引的眼中,該內(nèi)容永遠不會存在,因為它不是內(nèi)容豐富的!您需要做的是將內(nèi)容實際包含在您的 HTML 中,并使用 JS 來簡單地(簡單來說,隱藏它)并根據(jù)用戶操作顯示其余內(nèi)容!
記住“內(nèi)容為王”
我很快為你模擬了一個例子(可以做得更好,但會幫助你朝著正確的方向前進)(使用 jQuery,這是一個現(xiàn)代的 JS 庫)。如果您不知道它,建議您檢查一下,它實際上會讓您的生活比原始原生 JS 更輕松。
$(function() {
var truncate_element = $('.read-more'),
truncate_length = 100; // truncate length to 100 characters
truncate_element.each(function() {
var t = $(this).text();
if (t.length < truncate_length) return;
$(this).html(
t.slice(0, truncate_length) + '<span>... </span><span class="more">More</span>' +
'<span style="display:none;">' + t.slice(truncate_length, t.length) + ' <span class="less">Less</span></span>'
);
});
$('.more', truncate_element).click(function(event) {
event.preventDefault();
$(this).hide().prev().hide();
$(this).next().show();
});
$('.less', truncate_element).click(function(event) {
event.preventDefault();
$(this).parent().hide().prev().show().prev().show();
});
});
.more,.less { cursor: pointer: text-decoration: underline; background: black; color: white; padding: 5px 10px; display: inline-block; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<p class="read-more">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
我半同意的盧卡斯的解決方案不需要在表單元素中,如果它不是必須的話,但是關(guān)于刪除 href="" 的建議并不是一個好主意,不僅是無效的標記,而且在你的情況下是不需要的. 使用帶有HREF錨我只建議作為備用目標的喜歡網(wǎng)頁上的其他內(nèi)容的元素href="#content",所以如果JS被禁用或損壞可能向下導航到一些更多的內(nèi)容,但在你的情況下(基于問題),你不完全需要使用鏈接元素。
順便說一句,在上面的示例中,您可以將類“read-more”添加到您希望它截斷的任何元素中,并在單個頁面上使用更多和更少(如示例)和任意次數(shù)。
今日課程:考慮到 OOJ 編寫代碼,如果想重用函數(shù)使用類,請避免通過 JS 編寫內(nèi)容并在 HTML 中包含。
添加回答
舉報