【问题标题】:How to get the value of <select> inside <td> only if <select> tag presents?仅当 <select> 标签出现时,如何在 <td> 中获取 <select> 的值?
【发布时间】:2018-10-02 18:01:46
【问题描述】:

我有一个带有相关 js 文件的 HTML 页面。目的是将插入到表中的数据转换为 JSON 文件。用户可以编辑表格单元格,然后单击按钮,以便 Javascript 文件解析数据并将其作为 Ajax 请求发送到服务器上的 PHP 文件。然后 PHP 文件将数据作为文件存储在服务器上并将链接发回。 对于标签,我需要使用 val() 而不是 text() 来获取选定的值。但是,val() 返回一个空字符串。如何让它正确返回值?

var $TABLE = $('#table');
var $BTN = $('#export-btn');
var $EXPORT = $('#export');

$('.table-add').click(function () {
  var $clone = $TABLE.find('tr.hide').clone(true).removeClass('hide table-line');
  $TABLE.find('table').append($clone);
});

$('.table-remove').click(function () {
  $(this).parents('tr').detach();
});

$('.table-up').click(function () {
  var $row = $(this).parents('tr');
  if ($row.index() === 1) return; // Don't go above the header
  $row.prev().before($row.get(0));
});

$('.table-down').click(function () {
  var $row = $(this).parents('tr');
  $row.next().after($row.get(0));
});

// A few jQuery helpers for exporting only
jQuery.fn.pop = [].pop;
jQuery.fn.shift = [].shift;

$BTN.click(function () {
	//alert("ok");
  var $rows = $TABLE.find('tr:not(:hidden)');
  var headers = [];
  var data = [];
  
  // Get the headers (add special header logic here)
  $($rows.shift()).find('th:not(:empty)').each(function () {
    headers.push($(this).text().toLowerCase());
  });
  
  // Turn all existing rows into a loopable array
  $rows.each(function () {
    var $td = $(this).find('td');
    var h = {};
    // Use the headers from earlier to name our hash keys
    headers.forEach(function (header, i) {
      h[header] = $td.eq(i).val();  
		alert($td.eq(i).val());
    });
    
    data.push(h);
  });
  
  // Output the result
  normaldata = JSON.stringify(data);
  $.ajax({
      type: "POST",
      url: "filemaker.php",
      data:  {"data":normaldata},
      success: function(output) {

         
		var a = document.createElement('a');
		a.href = 'data.gmp'
		a.download = "data.gmp";
		a.click();
		//alert("reached here");
    }
});

  
});
.table-editable {
  position: relative;
}
.table-editable .glyphicon {
  font-size: 20px;
}

.table-remove {
  color: #700;
  cursor: pointer;
}
.table-remove:hover {
  color: #f00;
}

.table-up, .table-down {
  color: #007;
  cursor: pointer;
}
.table-up:hover, .table-down:hover {
  color: #00f;
}

.table-add {
  color: #070;
  cursor: pointer;
  position: absolute;
  top: 8px;
  right: 0;
}
.table-add:hover {
  color: #0b0;
}
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>HTML5 Editable Table</title>
  
  
 <link rel='stylesheet' href='http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css'>
<link rel='stylesheet' href='http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css'>

      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>
<a href='text.html' >aa</a>
  <div class="container">
  <h1>HTML5 Editable Table</h1>
  <p>Through the powers of <strong>contenteditable</strong> and some simple jQuery you can easily create a custom editable table. No need for a robust JavaScript library anymore these days.</p>
  
  <ul>
    <li>An editable table that exports a hash array. Dynamically compiles rows from headers</li> 
    <li>Simple / powerful features such as add row, remove row, move row up/down.</li>
  </ul>
  
  <div id="table" class="table-editable">
    <span class="table-add glyphicon glyphicon-plus"></span>
    <table class="table">
      <tr>
        <th>Type</th>
        <th>Doctor</th>
        <th>Specialization</th>
        <th>City</th>
        <th>Area</th>
        <th>Rank</th>
        <th></th>
        <th></th>
      </tr>
      <tr>
        <td contenteditable="true"> 
		<select> 
			<option value='pharmacist'>Pharmacist</option>
			<option value='doctor'>Doctor</option>
		</select>
	  </td>
        <td contenteditable="true">stir-fry</td>
        <td contenteditable="true">stir-fry</td>
        <td contenteditable="true">stir-fry</td>
        <td contenteditable="true">stir-fry</td>
         <td contenteditable="true"> 
		<select> 
			<option value='A+'>A+</option>
			<option value='A'>A</option>
			<option value='B'>B</option>
			<option value='C'>C</option>
		</select>
	  </td>
        <td>
          <span class="table-remove glyphicon glyphicon-remove"></span>
        </td>
    
      </tr>
      <!-- This is our clonable table line -->
      <tr class="hide">
	   <td contenteditable="true"> 
		<select> 
			<option value='pharmacist'>Pharmacist</option>
			<option value='doctor'>Doctor</option>
		</select>
	  </td>
        <td contenteditable="true">stir-fry</td>
        <td contenteditable="true">stir-fry</td>
        <td contenteditable="true">stir-fry</td>
        <td contenteditable="true">stir-fry</td>
        <td contenteditable="true"> 
		<select> 
			<option value='A+'>A+</option>
			<option value='A'>A</option>
			<option value='B'>B</option>
			<option value='C'>C</option>
		</select>
	  </td>
        <td>
          <span class="table-remove glyphicon glyphicon-remove"></span>
        </td>
 
      </tr>
    </table>
  </div>
  
  <button id="export-btn" class="btn btn-primary">Export Data</button>
  <p id="export"></p>
</div>
  <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js'></script>
<script src='https://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore.js'></script>

  

    <script  src="js/index.js"></script>




</body>

</html>

【问题讨论】:

  • .text() 和 .val() 返回完全不同的数据。第一个为您提供标签内的文本内容,另一个value 属性。
  • @vlaz 我知道,但这就是问题所在,为什么我没有得到价值?
  • &lt;td&gt; 元素没有值。 “.val() 方法主要用于获取input、select 和textarea 等表单元素的值。” -- val()
  • @showdev 谢谢。是否有任何解决方法可以从 内的

标签: javascript jquery html


【解决方案1】:

给定以下 jQuery 方法:

.val()方法主要用于获取input、select、textarea等表单元素的值。

.text() 方法的结果是一个包含所有匹配元素的组合文本的字符串。

对于每个表格单元格,您似乎想要返回子 &lt;select&gt; 的 val()(如果存在),否则返回 &lt;td&gt; 的 text()。

使用JavaScript的logical OR operator,我们可以根据存在的情况选择text()或val():

逻辑或 (||)
expr1 || expr2
如果可以转换为 true,则返回 expr1;否则,返回 expr2。

像这样:

$select.val() || $td.text()

这是一个例子:

var $TABLE = $('#table');
var $BTN = $('#export-btn');
var $EXPORT = $('#export');

$('.table-add').click(function() {
  var $clone = $TABLE.find('tr.hide').clone(true).removeClass('hide table-line');
  $TABLE.find('table').append($clone);
});

$('.table-remove').click(function() {
  $(this).parents('tr').detach();
});

$('.table-up').click(function() {
  var $row = $(this).parents('tr');
  if ($row.index() === 1) return; // Don't go above the header
  $row.prev().before($row.get(0));
});

$('.table-down').click(function() {
  var $row = $(this).parents('tr');
  $row.next().after($row.get(0));
});

// A few jQuery helpers for exporting only
jQuery.fn.pop = [].pop;
jQuery.fn.shift = [].shift;

$BTN.click(function() {
  //alert("ok");
  var $rows = $TABLE.find('tr:not(:hidden)');
  var headers = [];
  var data = [];

  // Get the headers (add special header logic here)
  $($rows.shift()).find('th:not(:empty)').each(function() {
    headers.push($(this).text().toLowerCase());
  });

  // Turn all existing rows into a loopable array
  $rows.each(function() {
    var $tds = $(this).find('td');
    var h = {};
    // Use the headers from earlier to name our hash keys
    headers.forEach(function(header, i) {
      var $td = $tds.eq(i);
      var $select = $td.find('select');
      h[header] = $select.val() || $td.text();
      console.log(h[header]);
    });
  });

});
.table-editable {
  position: relative;
}

.table-editable .glyphicon {
  font-size: 20px;
}

.table-remove {
  color: #700;
  cursor: pointer;
}

.table-remove:hover {
  color: #f00;
}

.table-up,
.table-down {
  color: #007;
  cursor: pointer;
}

.table-up:hover,
.table-down:hover {
  color: #00f;
}

.table-add {
  color: #070;
  cursor: pointer;
  position: absolute;
  top: 8px;
  right: 0;
}

.table-add:hover {
  color: #0b0;
}
<link rel='stylesheet' href='http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css'>
<link rel='stylesheet' href='http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css'>

<div id="table" class="table-editable">
  <span class="table-add glyphicon glyphicon-plus"></span>
  <table class="table">
    <tr>
      <th>Type</th>
      <th>Doctor</th>
      <th>Specialization</th>
      <th>City</th>
      <th>Area</th>
      <th>Rank</th>
      <th></th>
      <th></th>
    </tr>
    <tr>
      <td contenteditable="true">
        <select>
          <option value='pharmacist'>Pharmacist</option>
          <option value='doctor'>Doctor</option>
        </select>
      </td>
      <td contenteditable="true">stir-fry</td>
      <td contenteditable="true">stir-fry</td>
      <td contenteditable="true">stir-fry</td>
      <td contenteditable="true">stir-fry</td>
      <td contenteditable="true">
        <select>
          <option value='A+'>A+</option>
          <option value='A'>A</option>
          <option value='B'>B</option>
          <option value='C'>C</option>
        </select>
      </td>
      <td>
        <span class="table-remove glyphicon glyphicon-remove"></span>
      </td>

    </tr>
    <!-- This is our clonable table line -->
    <tr class="hide">
      <td contenteditable="true">
        <select>
          <option value='pharmacist'>Pharmacist</option>
          <option value='doctor'>Doctor</option>
        </select>
      </td>
      <td contenteditable="true">stir-fry</td>
      <td contenteditable="true">stir-fry</td>
      <td contenteditable="true">stir-fry</td>
      <td contenteditable="true">stir-fry</td>
      <td contenteditable="true">
        <select>
          <option value='A+'>A+</option>
          <option value='A'>A</option>
          <option value='B'>B</option>
          <option value='C'>C</option>
        </select>
      </td>
      <td>
        <span class="table-remove glyphicon glyphicon-remove"></span>
      </td>

    </tr>
  </table>
</div>

<button id="export-btn" class="btn btn-primary">Export Data</button>
<p id="export"></p>

<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js'></script>
<script src='https://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore.js'></script>

【讨论】:

    【解决方案2】:

    你的算法($td.eq(i))的第一个回报是

    <td contenteditable="true"> 
        <select> 
            <option value="pharmacist">Pharmacist</option>
            <option value="doctor">Doctor</option>
        </select>
    </td>
    

    而&lt;td contenteditable="true"&gt; 没有属性值,所以你有空值

    第二个值是

    <td contenteditable="true">stir-fry</td>
    

    它没有相同的属性值,所以也返回 null

    只需使用 .text() 即可。因为 .text() 只会得到标签中的文本

    我希望我能帮助并理解我所说的哈哈......

    【讨论】:

    • 问题已经回答。但是,对于其中不包含
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-21
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    • 2019-11-12
    相关资源
    最近更新 更多