javascript - 仅当 <select> 标签存在时,如何获取 <td> 内 <select> 的值?

标签 javascript jquery html

我有一个 HTML 页面及其关联的 js 文件。目的是将插入表中的数据转换为 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>

最佳答案

给定以下 jQuery 方法:

The .val() method is primarily used to get the values of form elements such as input, select and textarea.

The result of the .text() method is a string containing the combined text of all matched elements.

对于每个表格单元格,您似乎想要返回 val() child 的<select> ,如果存在的话,并且 text() <td>的否则。

使用 JavaScript 的 logical OR operator ,我们可以选择text()val()取决于哪个存在:

Logical OR (||)
expr1 || expr2
Returns expr1 if it can be converted to true; otherwise, returns 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>

关于javascript - 仅当 <select> 标签存在时,如何获取 <td> 内 <select> 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52613910/

相关文章:

javascript - Angular 4/5 : Load dev and prod scripts (3rd party)

javascript - 如何从外部文件运行函数作为表单的 Action ?

javascript - 如何用jQuery调用放置在另一个函数中的函数,而不修改原始代码?

jquery - Mobile Safari 滚动势头不起作用

javascript - 调用 jQuery 的 SlideUp 函数时,在视口(viewport)中保留单击的链接

javascript - 如何访问 Angular JS 模板指令中设置的值,例如 “ng-class?”

javascript - 在 JavaScript 中评估屏幕阅读器的当前状态

jQuery If-Else 代码片段的 JavaScript 简写

javascript - 限制滚动到目标 id

html - Div 超过 2 个其他 div?