[英]How to get the value of h1 tag using JS?
Vanilla JavaScript 解决方案(不需要框架):
var h1Text = document.querySelector(".entry-title").textContent;
你可以用jquery吗? 如果是这样,当您从 jquery 单击按钮时获取 h1 值,然后使用查询字符串发送到其他页面。
已编辑
将页面中的 jquery 文件添加到用户 jquery 功能。 并且您需要将函数放入 $(document).ready() 函数中,以便将该函数附加到对象中。
您可以在https://learn.jquery.com/ 中了解有关 jquery 的更多信息。
<script src="https://code.jquery.com/jquery-2.2.0.min.js"/>
<script>
$(document).ready(function(){
$('.application_button').click(function(){
var headervalue = $(".entry-title").text();
window.location = "http://homecredit.ph/testEnvironment/4537-2/?position="+headervalue;
});
});
</script>
使用您在普通 js 中给出标题的类使用以下内容。
var x = document.getElementsByClassName('entry-title').value;
console.log(x); //outputs collections trainer
如果你使用 jQuery 那么它的
$('.entry-title').text
希望有帮助。
如果您只想在单击按钮后获取 h1 值,则需要为按钮放置 onclick。
$.(document).ready(function(){
var header1Text ='';
$('.application_button').onclick(function(){
header1Text = $('h1').html();
});
//To display it in whichever textbox you want:
$('#GivesomeIDtoYourTextBox').val(header1Text);
});
PS:您还需要将 jquery 源包含到您的页面中。
jQuery:获取 H1 值
var gValue=jQuery("header h1.entry-title").text();
alert(gValue);
由于您需要在其他页面上获取值,因此您可以通过 QueryString 或使用 HTML5 LocalStorage 示例代码发送值:
var first_page_h1_Value=jQuery("header h1.entry-title").text();
var second_page_h1_Value=jQuery("header h1.entry-title").text();
localStorage.setItem("FirstPage", first_page_h1_Value);
localStorage.setItem("SecondPage", second_page_h1_Value);
在第三页上,您可以获得两页标题文本
alert(localStorage.FirstPage);
alert(localStorage.SecondPage);
如果您使用的是 Jquery,那么我建议您将 id 赋予您的 H1 标签,假设您的 H1 标签的 id 是“h1Title”。 HTML:
<h1 id="h1Title">Heading here</h1>
然后为了获得你在 JQuery 中编写的标题:
var title = $("#h1Title").text();
//To Check Whether you are getting text or not
console.log("title :"+title);
这样,您将获得标题的文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.