简体   繁体   English

如何从javascript函数中的html获取数据值?

[英]how to get data value from html in javascript function?

Hi I'm a beginner of jquery and ajax. 嗨,我是jquery和ajax的初学者。 This is my code: 这是我的代码:

.html html的

<li class="list-group-item">        
    <h2>Vocabulary</h2>
    <h4>
      <span class="label label-success">Like Name</span>  
      <span class="label label-danger">GEPT</span>
      <button type="button" id="collapsible" class="btn btn-default" data-toggle="collapse" data-target="#intro" data-word="good" onclick="loadXMLDoc()">
        <span class="glyphicon glyphicon-plus"></span>
      </button>
    </h4>
    <div class="collapse" id="intro">
      <div class="detail">
        <img src='http://www.michigan.com/assets/images/loading-module.gif'/>
      </div>         
    </div>
  </li>
  <li class="list-group-item">    

javascript: JavaScript的:

function loadXMLDoc()
{
  var xmlhttp;
  var word = $(this).data("word");
  var path='get_word_detail.php?word='+word;
  if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }else{// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function(){
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
  {
    document.getElementById("intro").innerHTML=xmlhttp.responseText;
  }
}
xmlhttp.open("GET",path,true);
xmlhttp.send();

} }

My page contain a list with many collapsed list items. 我的页面包含一个列表,其中包含许多折叠的列表项。 Every list item containing a button to expand the content of the item. 每个列表项都包含一个用于扩展项内容的按钮。

i want to get the "data-word" from html but it didnt work, Do anyone know how to do it correctly and whether it's possible for me to just pass the parameter from html tag like "onclick="loadXMLDoc("good")"? 我想从html获取“数据字”,但是它没有用,有人知道如何正确执行吗,以及是否有可能我只通过html标签传递参数,例如“ onclick =“ loadXMLDoc(” good“) “?

Thanks 谢谢

use attr function of jquery 使用jQuery的attr功能

$("#collapsible").attr("data-word");

EDIT 编辑

$(".btn").click(function(){
alert($(this).attr("data-word"));
});

you can use the below code 您可以使用以下代码

function loadXMLDoc(evt)
{
var element = evt.target;
  var xmlhttp;
  var word = $(element).data("word");
...
}

You are making some mix of jQuery and pure js, try to make it one way. 您正在混合使用jQuery和纯js,请尝试采用一种方法。 But if you want to launch your load func on click without adding onclick attr to html tag use jQuery: 但是,如果您想在点击时启动加载功能而不向HTML标签添加onclick属性,请使用jQuery:

$(document).ready(function(){
  $('#yourBtnId').click(function(){
     loadXMLDoc();
 })
});

If I correcltly understood the question. 如果我正确理解了这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM